Updated the 19 build version to 20090123
[moodle.git] / lib / datalib.php
blob7c78540cfbc8efcdfba8ab564802f5bdc70b980e
1 <?php // $Id$
2 /**
3 * Library of functions for database manipulation.
5 * Other main libraries:
6 * - weblib.php - functions that produce web output
7 * - moodlelib.php - general-purpose Moodle functions
8 * @author Martin Dougiamas and many others
9 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
10 * @package moodlecore
13 /// Some constants
14 define('LASTACCESS_UPDATE_SECS', 60); /// Number of seconds to wait before
15 /// updating lastaccess information in DB.
17 /**
18 * Escape all dangerous characters in a data record
20 * $dataobject is an object containing needed data
21 * Run over each field exectuting addslashes() function
22 * to escape SQL unfriendly characters (e.g. quotes)
23 * Handy when writing back data read from the database
25 * @param $dataobject Object containing the database record
26 * @return object Same object with neccessary characters escaped
28 function addslashes_object( $dataobject ) {
29 $a = get_object_vars( $dataobject);
30 foreach ($a as $key=>$value) {
31 $a[$key] = addslashes( $value );
33 return (object)$a;
36 /// USER DATABASE ////////////////////////////////////////////////
38 /**
39 * Returns $user object of the main admin user
40 * primary admin = admin with lowest role_assignment id among admins
41 * @uses $CFG
42 * @return object(admin) An associative array representing the admin user.
44 function get_admin () {
46 global $CFG;
47 static $myadmin;
49 if (isset($myadmin)) {
50 return $myadmin;
53 if ( $admins = get_admins() ) {
54 foreach ($admins as $admin) {
55 $myadmin = $admin;
56 return $admin; // ie the first one
58 } else {
59 return false;
63 /**
64 * Returns list of all admins, using 1 DB query. It depends on DB schema v1.7
65 * but does not depend on the v1.9 datastructures (context.path, etc).
67 * @uses $CFG
68 * @return object
70 function get_admins() {
72 global $CFG;
74 $sql = "SELECT ra.userid, SUM(rc.permission) AS permission, MIN(ra.id) AS adminid
75 FROM " . $CFG->prefix . "role_capabilities rc
76 JOIN " . $CFG->prefix . "context ctx
77 ON ctx.id=rc.contextid
78 JOIN " . $CFG->prefix . "role_assignments ra
79 ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
80 WHERE ctx.contextlevel=10
81 AND rc.capability IN ('moodle/site:config',
82 'moodle/legacy:admin',
83 'moodle/site:doanything')
84 GROUP BY ra.userid
85 HAVING SUM(rc.permission) > 0";
87 $sql = "SELECT u.*, ra.adminid
88 FROM " . $CFG->prefix . "user u
89 JOIN ($sql) ra
90 ON u.id=ra.userid
91 ORDER BY ra.adminid ASC";
93 return get_records_sql($sql);
97 function get_courses_in_metacourse($metacourseid) {
98 global $CFG;
100 $sql = "SELECT c.id,c.shortname,c.fullname FROM {$CFG->prefix}course c, {$CFG->prefix}course_meta mc WHERE mc.parent_course = $metacourseid
101 AND mc.child_course = c.id ORDER BY c.shortname";
103 return get_records_sql($sql);
106 function get_courses_notin_metacourse($metacourseid,$count=false) {
108 global $CFG;
110 if ($count) {
111 $sql = "SELECT COUNT(c.id)";
112 } else {
113 $sql = "SELECT c.id,c.shortname,c.fullname";
116 $alreadycourses = get_courses_in_metacourse($metacourseid);
118 $sql .= " FROM {$CFG->prefix}course c WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
119 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1 ".((empty($count)) ? " ORDER BY c.shortname" : "");
121 return get_records_sql($sql);
124 function count_courses_notin_metacourse($metacourseid) {
125 global $CFG;
127 $alreadycourses = get_courses_in_metacourse($metacourseid);
129 $sql = "SELECT COUNT(c.id) AS notin FROM {$CFG->prefix}course c
130 WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
131 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1";
133 if (!$count = get_record_sql($sql)) {
134 return 0;
137 return $count->notin;
141 * Search through course users
143 * If $coursid specifies the site course then this function searches
144 * through all undeleted and confirmed users
146 * @uses $CFG
147 * @uses SITEID
148 * @param int $courseid The course in question.
149 * @param int $groupid The group in question.
150 * @param string $searchtext ?
151 * @param string $sort ?
152 * @param string $exceptions ?
153 * @return object
155 function search_users($courseid, $groupid, $searchtext, $sort='', $exceptions='') {
156 global $CFG;
158 $LIKE = sql_ilike();
159 $fullname = sql_fullname('u.firstname', 'u.lastname');
161 if (!empty($exceptions)) {
162 $except = ' AND u.id NOT IN ('. $exceptions .') ';
163 } else {
164 $except = '';
167 if (!empty($sort)) {
168 $order = ' ORDER BY '. $sort;
169 } else {
170 $order = '';
173 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
175 if (!$courseid or $courseid == SITEID) {
176 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
177 FROM {$CFG->prefix}user u
178 WHERE $select
179 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
180 $except $order");
181 } else {
183 if ($groupid) {
184 //TODO:check. Remove group DB dependencies.
185 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
186 FROM {$CFG->prefix}user u,
187 {$CFG->prefix}groups_members gm
188 WHERE $select AND gm.groupid = '$groupid' AND gm.userid = u.id
189 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
190 $except $order");
191 } else {
192 $context = get_context_instance(CONTEXT_COURSE, $courseid);
193 $contextlists = get_related_contexts_string($context);
194 $users = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
195 FROM {$CFG->prefix}user u,
196 {$CFG->prefix}role_assignments ra
197 WHERE $select AND ra.contextid $contextlists AND ra.userid = u.id
198 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
199 $except $order");
201 return $users;
207 * Returns a list of all site users
208 * Obsolete, just calls get_course_users(SITEID)
210 * @uses SITEID
211 * @deprecated Use {@link get_course_users()} instead.
212 * @param string $fields A comma separated list of fields to be returned from the chosen table.
213 * @param string $exceptions A comma separated list of user->id to be skiped in the result returned by the function
214 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
215 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
216 * @return object|false {@link $USER} records or false if error.
218 function get_site_users($sort='u.lastaccess DESC', $fields='*', $exceptions='', $limitfrom='', $limitnum='') {
220 return get_course_users(SITEID, $sort, $exceptions, $fields, $limitfrom, $limitnum);
225 * Returns a subset of users
227 * @uses $CFG
228 * @param bool $get If false then only a count of the records is returned
229 * @param string $search A simple string to search for
230 * @param bool $confirmed A switch to allow/disallow unconfirmed users
231 * @param array(int) $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
232 * @param string $sort A SQL snippet for the sorting criteria to use
233 * @param string $firstinitial ?
234 * @param string $lastinitial ?
235 * @param string $page ?
236 * @param string $recordsperpage ?
237 * @param string $fields A comma separated list of fields to be returned from the chosen table.
238 * @return object|false|int {@link $USER} records unless get is false in which case the integer count of the records found is returned. False is returned if an error is encountered.
240 function get_users($get=true, $search='', $confirmed=false, $exceptions='', $sort='firstname ASC',
241 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='') {
243 global $CFG;
245 if ($get && !$recordsperpage) {
246 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
247 'On large installations, this will probably cause an out of memory error. ' .
248 'Please think again and change your code so that it does not try to ' .
249 'load so much data into memory.', DEBUG_DEVELOPER);
252 $LIKE = sql_ilike();
253 $fullname = sql_fullname();
255 $select = 'username <> \'guest\' AND deleted = 0';
257 if (!empty($search)){
258 $search = trim($search);
259 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
262 if ($confirmed) {
263 $select .= ' AND confirmed = \'1\' ';
266 if ($exceptions) {
267 $select .= ' AND id NOT IN ('. $exceptions .') ';
270 if ($firstinitial) {
271 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\'';
273 if ($lastinitial) {
274 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\'';
277 if ($extraselect) {
278 $select .= " AND $extraselect ";
281 if ($get) {
282 return get_records_select('user', $select, $sort, $fields, $page, $recordsperpage);
283 } else {
284 return count_records_select('user', $select);
290 * shortdesc (optional)
292 * longdesc
294 * @uses $CFG
295 * @param string $sort ?
296 * @param string $dir ?
297 * @param int $categoryid ?
298 * @param int $categoryid ?
299 * @param string $search ?
300 * @param string $firstinitial ?
301 * @param string $lastinitial ?
302 * @returnobject {@link $USER} records
303 * @todo Finish documenting this function
306 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
307 $search='', $firstinitial='', $lastinitial='', $extraselect='') {
309 global $CFG;
311 $LIKE = sql_ilike();
312 $fullname = sql_fullname();
314 $select = "deleted <> '1'";
316 if (!empty($search)) {
317 $search = trim($search);
318 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%' OR username='$search') ";
321 if ($firstinitial) {
322 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\' ';
325 if ($lastinitial) {
326 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\' ';
329 if ($extraselect) {
330 $select .= " AND $extraselect ";
333 if ($sort) {
334 $sort = ' ORDER BY '. $sort .' '. $dir;
337 /// warning: will return UNCONFIRMED USERS
338 return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
339 FROM {$CFG->prefix}user
340 WHERE $select $sort", $page, $recordsperpage);
346 * Full list of users that have confirmed their accounts.
348 * @uses $CFG
349 * @return object
351 function get_users_confirmed() {
352 global $CFG;
353 return get_records_sql("SELECT *
354 FROM {$CFG->prefix}user
355 WHERE confirmed = 1
356 AND deleted = 0
357 AND username <> 'guest'");
361 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
365 * Returns $course object of the top-level site.
367 * @return course A {@link $COURSE} object for the site
369 function get_site() {
371 global $SITE;
373 if (!empty($SITE->id)) { // We already have a global to use, so return that
374 return $SITE;
377 if ($course = get_record('course', 'category', 0)) {
378 return $course;
379 } else {
380 return false;
385 * Returns list of courses, for whole site, or category
387 * Returns list of courses, for whole site, or category
388 * Important: Using c.* for fields is extremely expensive because
389 * we are using distinct. You almost _NEVER_ need all the fields
390 * in such a large SELECT
392 * @param type description
395 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
397 global $USER, $CFG;
399 if ($categoryid != "all" && is_numeric($categoryid)) {
400 $categoryselect = "WHERE c.category = '$categoryid'";
401 } else {
402 $categoryselect = "";
405 if (empty($sort)) {
406 $sortstatement = "";
407 } else {
408 $sortstatement = "ORDER BY $sort";
411 $visiblecourses = array();
413 // pull out all course matching the cat
414 if ($courses = get_records_sql("SELECT $fields,
415 ctx.id AS ctxid, ctx.path AS ctxpath,
416 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
417 FROM {$CFG->prefix}course c
418 JOIN {$CFG->prefix}context ctx
419 ON (c.id = ctx.instanceid
420 AND ctx.contextlevel=".CONTEXT_COURSE.")
421 $categoryselect
422 $sortstatement")) {
424 // loop throught them
425 foreach ($courses as $course) {
426 $course = make_context_subobj($course);
427 if (isset($course->visible) && $course->visible <= 0) {
428 // for hidden courses, require visibility check
429 if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
430 $visiblecourses [] = $course;
432 } else {
433 $visiblecourses [] = $course;
437 return $visiblecourses;
440 $teachertable = "";
441 $visiblecourses = "";
442 $sqland = "";
443 if (!empty($categoryselect)) {
444 $sqland = "AND ";
446 if (!empty($USER->id)) { // May need to check they are a teacher
447 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
448 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
449 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course = c.id";
451 } else {
452 $visiblecourses = "$sqland c.visible > 0";
455 if ($categoryselect or $visiblecourses) {
456 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
457 } else {
458 $selectsql = "{$CFG->prefix}course c $teachertable";
461 $extrafield = str_replace('ASC','',$sort);
462 $extrafield = str_replace('DESC','',$extrafield);
463 $extrafield = trim($extrafield);
464 if (!empty($extrafield)) {
465 $extrafield = ','.$extrafield;
467 return get_records_sql("SELECT ".((!empty($teachertable)) ? " DISTINCT " : "")." $fields $extrafield FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : ""));
473 * Returns list of courses, for whole site, or category
475 * Similar to get_courses, but allows paging
476 * Important: Using c.* for fields is extremely expensive because
477 * we are using distinct. You almost _NEVER_ need all the fields
478 * in such a large SELECT
480 * @param type description
483 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
484 &$totalcount, $limitfrom="", $limitnum="") {
486 global $USER, $CFG;
488 $categoryselect = "";
489 if ($categoryid != "all" && is_numeric($categoryid)) {
490 $categoryselect = "WHERE c.category = '$categoryid'";
491 } else {
492 $categoryselect = "";
495 // pull out all course matching the cat
496 $visiblecourses = array();
497 if (!($rs = get_recordset_sql("SELECT $fields,
498 ctx.id AS ctxid, ctx.path AS ctxpath,
499 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
500 FROM {$CFG->prefix}course c
501 JOIN {$CFG->prefix}context ctx
502 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
503 $categoryselect
504 ORDER BY $sort"))) {
505 return $visiblecourses;
507 $totalcount = 0;
509 if (!$limitfrom) {
510 $limitfrom = 0;
513 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
514 while ($course = rs_fetch_next_record($rs)) {
515 $course = make_context_subobj($course);
516 if ($course->visible <= 0) {
517 // for hidden courses, require visibility check
518 if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
519 $totalcount++;
520 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
521 $visiblecourses [] = $course;
524 } else {
525 $totalcount++;
526 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
527 $visiblecourses [] = $course;
531 rs_close($rs);
532 return $visiblecourses;
536 $categoryselect = "";
537 if ($categoryid != "all" && is_numeric($categoryid)) {
538 $categoryselect = "c.category = '$categoryid'";
541 $teachertable = "";
542 $visiblecourses = "";
543 $sqland = "";
544 if (!empty($categoryselect)) {
545 $sqland = "AND ";
547 if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
548 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
549 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
550 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
552 } else {
553 $visiblecourses = "$sqland c.visible > 0";
556 if ($limitfrom !== "") {
557 $limit = sql_paging_limit($limitfrom, $limitnum);
558 } else {
559 $limit = "";
562 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
564 $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
566 return get_records_sql("SELECT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
571 * Retrieve course records with the course managers and other related records
572 * that we need for print_course(). This allows print_courses() to do its job
573 * in a constant number of DB queries, regardless of the number of courses,
574 * role assignments, etc.
576 * The returned array is indexed on c.id, and each course will have
577 * - $course->context - a context obj
578 * - $course->managers - array containing RA objects that include a $user obj
579 * with the minimal fields needed for fullname()
582 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
584 * The plan is to
586 * - Grab the courses JOINed w/context
588 * - Grab the interesting course-manager RAs
589 * JOINed with a base user obj and add them to each course
591 * So as to do all the work in 2 DB queries. The RA+user JOIN
592 * ends up being pretty expensive if it happens over _all_
593 * courses on a large site. (Are we surprised!?)
595 * So this should _never_ get called with 'all' on a large site.
598 global $USER, $CFG;
600 $allcats = false; // bool flag
601 if ($categoryid === 'all') {
602 $categoryclause = '';
603 $allcats = true;
604 } elseif (is_numeric($categoryid)) {
605 $categoryclause = "c.category = $categoryid";
606 } else {
607 debugging("Could not recognise categoryid = $categoryid");
608 $categoryclause = '';
611 $basefields = array('id', 'category', 'sortorder',
612 'shortname', 'fullname', 'idnumber',
613 'teacher', 'teachers', 'student', 'students',
614 'guest', 'startdate', 'visible',
615 'newsitems', 'cost', 'enrol',
616 'groupmode', 'groupmodeforce');
618 if (!is_null($fields) && is_string($fields)) {
619 if (empty($fields)) {
620 $fields = $basefields;
621 } else {
622 // turn the fields from a string to an array that
623 // get_user_courses_bycap() will like...
624 $fields = explode(',',$fields);
625 $fields = array_map('trim', $fields);
626 $fields = array_unique(array_merge($basefields, $fields));
628 } elseif (is_array($fields)) {
629 $fields = array_merge($basefields,$fields);
631 $coursefields = 'c.' .join(',c.', $fields);
633 if (empty($sort)) {
634 $sortstatement = "";
635 } else {
636 $sortstatement = "ORDER BY $sort";
639 $where = 'WHERE c.id != ' . SITEID;
640 if ($categoryclause !== ''){
641 $where = "$where AND $categoryclause";
644 // pull out all courses matching the cat
645 $sql = "SELECT $coursefields,
646 ctx.id AS ctxid, ctx.path AS ctxpath,
647 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
648 FROM {$CFG->prefix}course c
649 JOIN {$CFG->prefix}context ctx
650 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
651 $where
652 $sortstatement";
654 $catpaths = array();
655 $catpath = NULL;
656 if ($courses = get_records_sql($sql)) {
657 // loop on courses materialising
658 // the context, and prepping data to fetch the
659 // managers efficiently later...
660 foreach ($courses as $k => $course) {
661 $courses[$k] = make_context_subobj($courses[$k]);
662 $courses[$k]->managers = array();
663 if ($allcats === false) {
664 // single cat, so take just the first one...
665 if ($catpath === NULL) {
666 $catpath = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
668 } else {
669 // chop off the contextid of the course itself
670 // like dirname() does...
671 $catpaths[] = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
674 } else {
675 return array(); // no courses!
678 $CFG->coursemanager = trim($CFG->coursemanager);
679 if (empty($CFG->coursemanager)) {
680 return $courses;
683 $managerroles = split(',', $CFG->coursemanager);
684 $catctxids = '';
685 if (count($managerroles)) {
686 if ($allcats === true) {
687 $catpaths = array_unique($catpaths);
688 $ctxids = array();
689 foreach ($catpaths as $cpath) {
690 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
692 $ctxids = array_unique($ctxids);
693 $catctxids = implode( ',' , $ctxids);
694 unset($catpaths);
695 unset($cpath);
696 } else {
697 // take the ctx path from the first course
698 // as all categories will be the same...
699 $catpath = substr($catpath,1);
700 $catpath = preg_replace(':/\d+$:','',$catpath);
701 $catctxids = str_replace('/',',',$catpath);
703 if ($categoryclause !== '') {
704 $categoryclause = "AND $categoryclause";
707 * Note: Here we use a LEFT OUTER JOIN that can
708 * "optionally" match to avoid passing a ton of context
709 * ids in an IN() clause. Perhaps a subselect is faster.
711 * In any case, this SQL is not-so-nice over large sets of
712 * courses with no $categoryclause.
715 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
716 ra.hidden,
717 r.id AS roleid, r.name as rolename,
718 u.id AS userid, u.firstname, u.lastname
719 FROM {$CFG->prefix}role_assignments ra
720 JOIN {$CFG->prefix}context ctx
721 ON ra.contextid = ctx.id
722 JOIN {$CFG->prefix}user u
723 ON ra.userid = u.id
724 JOIN {$CFG->prefix}role r
725 ON ra.roleid = r.id
726 LEFT OUTER JOIN {$CFG->prefix}course c
727 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
728 WHERE ( c.id IS NOT NULL";
729 // under certain conditions, $catctxids is NULL
730 if($catctxids == NULL){
731 $sql .= ") ";
732 }else{
733 $sql .= " OR ra.contextid IN ($catctxids) )";
736 $sql .= "AND ra.roleid IN ({$CFG->coursemanager})
737 $categoryclause
738 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
739 $rs = get_recordset_sql($sql);
741 // This loop is fairly stupid as it stands - might get better
742 // results doing an initial pass clustering RAs by path.
743 while ($ra = rs_fetch_next_record($rs)) {
744 $user = new StdClass;
745 $user->id = $ra->userid; unset($ra->userid);
746 $user->firstname = $ra->firstname; unset($ra->firstname);
747 $user->lastname = $ra->lastname; unset($ra->lastname);
748 $ra->user = $user;
749 if ($ra->contextlevel == CONTEXT_SYSTEM) {
750 foreach ($courses as $k => $course) {
751 $courses[$k]->managers[] = $ra;
753 } elseif ($ra->contextlevel == CONTEXT_COURSECAT) {
754 if ($allcats === false) {
755 // It always applies
756 foreach ($courses as $k => $course) {
757 $courses[$k]->managers[] = $ra;
759 } else {
760 foreach ($courses as $k => $course) {
761 // Note that strpos() returns 0 as "matched at pos 0"
762 if (strpos($course->context->path, $ra->path.'/')===0) {
763 // Only add it to subpaths
764 $courses[$k]->managers[] = $ra;
768 } else { // course-level
769 if(!array_key_exists($ra->instanceid, $courses)) {
770 //this course is not in a list, probably a frontpage course
771 continue;
773 $courses[$ra->instanceid]->managers[] = $ra;
776 rs_close($rs);
779 return $courses;
783 * Convenience function - lists courses that a user has access to view.
785 * For admins and others with access to "every" course in the system, we should
786 * try to get courses with explicit RAs.
788 * NOTE: this function is heavily geared towards the perspective of the user
789 * passed in $userid. So it will hide courses that the user cannot see
790 * (for any reason) even if called from cron or from another $USER's
791 * perspective.
793 * If you really want to know what courses are assigned to the user,
794 * without any hiding or scheming, call the lower-level
795 * get_user_courses_bycap().
798 * Notes inherited from get_user_courses_bycap():
800 * - $fields is an array of fieldnames to ADD
801 * so name the fields you really need, which will
802 * be added and uniq'd
804 * - the course records have $c->context which is a fully
805 * valid context object. Saves you a query per course!
807 * @uses $CFG,$USER
808 * @param int $userid The user of interest
809 * @param string $sort the sortorder in the course table
810 * @param array $fields - names of _additional_ fields to return (also accepts a string)
811 * @param bool $doanything True if using the doanything flag
812 * @param int $limit Maximum number of records to return, or 0 for unlimited
813 * @return array {@link $COURSE} of course objects
815 function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
817 global $CFG,$USER;
819 // Guest's do not have any courses
820 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
821 if (has_capability('moodle/legacy:guest',$sitecontext,$userid,false)) {
822 return(array());
825 $basefields = array('id', 'category', 'sortorder',
826 'shortname', 'fullname', 'idnumber',
827 'teacher', 'teachers', 'student', 'students',
828 'guest', 'startdate', 'visible',
829 'newsitems', 'cost', 'enrol',
830 'groupmode', 'groupmodeforce');
832 if (!is_null($fields) && is_string($fields)) {
833 if (empty($fields)) {
834 $fields = $basefields;
835 } else {
836 // turn the fields from a string to an array that
837 // get_user_courses_bycap() will like...
838 $fields = explode(',',$fields);
839 $fields = array_map('trim', $fields);
840 $fields = array_unique(array_merge($basefields, $fields));
842 } elseif (is_array($fields)) {
843 $fields = array_unique(array_merge($basefields, $fields));
844 } else {
845 $fields = $basefields;
848 $orderby = '';
849 $sort = trim($sort);
850 if (!empty($sort)) {
851 $rawsorts = explode(',', $sort);
852 $sorts = array();
853 foreach ($rawsorts as $rawsort) {
854 $rawsort = trim($rawsort);
855 if (strpos($rawsort, 'c.') === 0) {
856 $rawsort = substr($rawsort, 2);
858 $sorts[] = trim($rawsort);
860 $sort = 'c.'.implode(',c.', $sorts);
861 $orderby = "ORDER BY $sort";
865 // Logged-in user - Check cached courses
867 // NOTE! it's a _string_ because
868 // - it's all we'll ever use
869 // - it serialises much more compact than an array
870 // this a big concern here - cost of serialise
871 // and unserialise gets huge as the session grows
873 // If the courses are too many - it won't be set
874 // for large numbers of courses, caching in the session
875 // has marginal benefits (costs too much, not
876 // worthwhile...) and we may hit SQL parser limits
877 // because we use IN()
879 if ($userid === $USER->id) {
880 if (isset($USER->loginascontext)
881 && $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
882 // list _only_ this course
883 // anything else is asking for trouble...
884 $courseids = $USER->loginascontext->instanceid;
885 } elseif (isset($USER->mycourses)
886 && is_string($USER->mycourses)) {
887 if ($USER->mycourses === '') {
888 // empty str means: user has no courses
889 // ... so do the easy thing...
890 return array();
891 } else {
892 $courseids = $USER->mycourses;
895 if (isset($courseids)) {
896 // The data massaging here MUST be kept in sync with
897 // get_user_courses_bycap() so we return
898 // the same...
899 // (but here we don't need to check has_cap)
900 $coursefields = 'c.' .join(',c.', $fields);
901 $sql = "SELECT $coursefields,
902 ctx.id AS ctxid, ctx.path AS ctxpath,
903 ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel,
904 cc.path AS categorypath
905 FROM {$CFG->prefix}course c
906 JOIN {$CFG->prefix}course_categories cc
907 ON c.category=cc.id
908 JOIN {$CFG->prefix}context ctx
909 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
910 WHERE c.id IN ($courseids)
911 $orderby";
912 $rs = get_recordset_sql($sql);
913 $courses = array();
914 $cc = 0; // keep count
915 while ($c = rs_fetch_next_record($rs)) {
916 // build the context obj
917 $c = make_context_subobj($c);
919 $courses[$c->id] = $c;
920 if ($limit > 0 && $cc++ > $limit) {
921 break;
924 rs_close($rs);
925 return $courses;
929 // Non-cached - get accessinfo
930 if ($userid === $USER->id && isset($USER->access)) {
931 $accessinfo = $USER->access;
932 } else {
933 $accessinfo = get_user_access_sitewide($userid);
937 $courses = get_user_courses_bycap($userid, 'moodle/course:view', $accessinfo,
938 $doanything, $sort, $fields,
939 $limit);
941 $cats = NULL;
942 // If we have to walk category visibility
943 // to eval course visibility, get the categories
944 if (empty($CFG->allowvisiblecoursesinhiddencategories)) {
945 $sql = "SELECT cc.id, cc.path, cc.visible,
946 ctx.id AS ctxid, ctx.path AS ctxpath,
947 ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel
948 FROM {$CFG->prefix}course_categories cc
949 JOIN {$CFG->prefix}context ctx ON (cc.id = ctx.instanceid)
950 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT."
951 ORDER BY cc.id";
952 $rs = get_recordset_sql($sql);
954 // Using a temporary array instead of $cats here, to avoid a "true" result when isnull($cats) further down
955 $categories = array();
956 while ($course_cat = rs_fetch_next_record($rs)) {
957 // build the context obj
958 $course_cat = make_context_subobj($course_cat);
959 $categories[$course_cat->id] = $course_cat;
961 rs_close($rs);
963 if (!empty($categories)) {
964 $cats = $categories;
967 unset($course_cat);
970 // Strangely, get_my_courses() is expected to return the
971 // array keyed on id, which messes up the sorting
972 // So do that, and also cache the ids in the session if appropriate
974 $kcourses = array();
975 $courses_count = count($courses);
976 $cacheids = NULL;
977 $vcatpaths = array();
978 if ($userid === $USER->id && $courses_count < 500) {
979 $cacheids = array();
981 for ($n=0; $n<$courses_count; $n++) {
984 // Check whether $USER (not $userid) can _actually_ see them
985 // Easy if $CFG->allowvisiblecoursesinhiddencategories
986 // is set, and we don't have to care about categories.
987 // Lots of work otherwise... (all in mem though!)
989 $cansee = false;
990 if (is_null($cats)) { // easy rules!
991 if ($courses[$n]->visible == true) {
992 $cansee = true;
993 } elseif (has_capability('moodle/course:viewhiddencourses',
994 $courses[$n]->context, $USER->id)) {
995 $cansee = true;
997 } else {
999 // Is the cat visible?
1000 // we have to assume it _is_ visible
1001 // so we can shortcut when we find a hidden one
1003 $viscat = true;
1004 $cpath = $courses[$n]->categorypath;
1005 if (isset($vcatpaths[$cpath])) {
1006 $viscat = $vcatpaths[$cpath];
1007 } else {
1008 $cpath = substr($cpath,1); // kill leading slash
1009 $cpath = explode('/',$cpath);
1010 $ccct = count($cpath);
1011 for ($m=0;$m<$ccct;$m++) {
1012 $ccid = $cpath[$m];
1013 if ($cats[$ccid]->visible==false) {
1014 $viscat = false;
1015 break;
1018 $vcatpaths[$courses[$n]->categorypath] = $viscat;
1022 // Perhaps it's actually visible to $USER
1023 // check moodle/category:viewhiddencategories
1025 // The name isn't obvious, but the description says
1026 // "See hidden categories" so the user shall see...
1027 // But also check if the allowvisiblecoursesinhiddencategories setting is true, and check for course visibility
1028 if ($viscat === false) {
1029 $catctx = $cats[$courses[$n]->category]->context;
1030 if (has_capability('moodle/category:viewhiddencategories', $catctx, $USER->id)) {
1031 $vcatpaths[$courses[$n]->categorypath] = true;
1032 $viscat = true;
1033 } elseif ($CFG->allowvisiblecoursesinhiddencategories && $courses[$n]->visible == true) {
1034 $viscat = true;
1039 // Decision matrix
1041 if ($viscat === true) {
1042 if ($courses[$n]->visible == true) {
1043 $cansee = true;
1044 } elseif (has_capability('moodle/course:viewhiddencourses',
1045 $courses[$n]->context, $USER->id)) {
1046 $cansee = true;
1050 if ($cansee === true) {
1051 $kcourses[$courses[$n]->id] = $courses[$n];
1052 if (is_array($cacheids)) {
1053 $cacheids[] = $courses[$n]->id;
1057 if (is_array($cacheids)) {
1058 // Only happens
1059 // - for the logged in user
1060 // - below the threshold (500)
1061 // empty string is _valid_
1062 $USER->mycourses = join(',',$cacheids);
1063 } elseif ($userid === $USER->id && isset($USER->mycourses)) {
1064 // cheap sanity check
1065 unset($USER->mycourses);
1068 return $kcourses;
1072 * A list of courses that match a search
1074 * @uses $CFG
1075 * @param array $searchterms ?
1076 * @param string $sort ?
1077 * @param int $page ?
1078 * @param int $recordsperpage ?
1079 * @param int $totalcount Passed in by reference. ?
1080 * @return object {@link $COURSE} records
1082 function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
1084 global $CFG;
1086 //to allow case-insensitive search for postgesql
1087 if ($CFG->dbfamily == 'postgres') {
1088 $LIKE = 'ILIKE';
1089 $NOTLIKE = 'NOT ILIKE'; // case-insensitive
1090 $REGEXP = '~*';
1091 $NOTREGEXP = '!~*';
1092 } else {
1093 $LIKE = 'LIKE';
1094 $NOTLIKE = 'NOT LIKE';
1095 $REGEXP = 'REGEXP';
1096 $NOTREGEXP = 'NOT REGEXP';
1099 $fullnamesearch = '';
1100 $summarysearch = '';
1102 foreach ($searchterms as $searchterm) {
1104 $NOT = ''; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1105 /// will use it to simulate the "-" operator with LIKE clause
1107 /// Under Oracle and MSSQL, trim the + and - operators and perform
1108 /// simpler LIKE (or NOT LIKE) queries
1109 if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
1110 if (substr($searchterm, 0, 1) == '-') {
1111 $NOT = ' NOT ';
1113 $searchterm = trim($searchterm, '+-');
1116 if ($fullnamesearch) {
1117 $fullnamesearch .= ' AND ';
1119 if ($summarysearch) {
1120 $summarysearch .= ' AND ';
1123 if (substr($searchterm,0,1) == '+') {
1124 $searchterm = substr($searchterm,1);
1125 $summarysearch .= " c.summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1126 $fullnamesearch .= " c.fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1127 } else if (substr($searchterm,0,1) == "-") {
1128 $searchterm = substr($searchterm,1);
1129 $summarysearch .= " c.summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1130 $fullnamesearch .= " c.fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1131 } else {
1132 $summarysearch .= ' summary '. $NOT . $LIKE .' \'%'. $searchterm .'%\' ';
1133 $fullnamesearch .= ' fullname '. $NOT . $LIKE .' \'%'. $searchterm .'%\' ';
1138 $sql = "SELECT c.*,
1139 ctx.id AS ctxid, ctx.path AS ctxpath,
1140 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1141 FROM {$CFG->prefix}course c
1142 JOIN {$CFG->prefix}context ctx
1143 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
1144 WHERE (( $fullnamesearch ) OR ( $summarysearch ))
1145 AND category > 0
1146 ORDER BY " . $sort;
1148 $courses = array();
1150 if ($rs = get_recordset_sql($sql)) {
1153 // Tiki pagination
1154 $limitfrom = $page * $recordsperpage;
1155 $limitto = $limitfrom + $recordsperpage;
1156 $c = 0; // counts how many visible courses we've seen
1158 while ($course = rs_fetch_next_record($rs)) {
1159 $course = make_context_subobj($course);
1160 if ($course->visible || has_capability('moodle/course:viewhiddencourses', $course->context)) {
1161 // Don't exit this loop till the end
1162 // we need to count all the visible courses
1163 // to update $totalcount
1164 if ($c >= $limitfrom && $c < $limitto) {
1165 $courses[] = $course;
1167 $c++;
1172 // our caller expects 2 bits of data - our return
1173 // array, and an updated $totalcount
1174 $totalcount = $c;
1175 return $courses;
1180 * Returns a sorted list of categories. Each category object has a context
1181 * property that is a context object.
1183 * When asking for $parent='none' it will return all the categories, regardless
1184 * of depth. Wheen asking for a specific parent, the default is to return
1185 * a "shallow" resultset. Pass false to $shallow and it will return all
1186 * the child categories as well.
1189 * @param string $parent The parent category if any
1190 * @param string $sort the sortorder
1191 * @param bool $shallow - set to false to get the children too
1192 * @return array of categories
1194 function get_categories($parent='none', $sort=NULL, $shallow=true) {
1195 global $CFG;
1197 if ($sort === NULL) {
1198 $sort = 'ORDER BY cc.sortorder ASC';
1199 } elseif ($sort ==='') {
1200 // leave it as empty
1201 } else {
1202 $sort = "ORDER BY $sort";
1205 if ($parent === 'none') {
1206 $sql = "SELECT cc.*,
1207 ctx.id AS ctxid, ctx.path AS ctxpath,
1208 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1209 FROM {$CFG->prefix}course_categories cc
1210 JOIN {$CFG->prefix}context ctx
1211 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
1212 $sort";
1213 } elseif ($shallow) {
1214 $parent = (int)$parent;
1215 $sql = "SELECT cc.*,
1216 ctx.id AS ctxid, ctx.path AS ctxpath,
1217 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1218 FROM {$CFG->prefix}course_categories cc
1219 JOIN {$CFG->prefix}context ctx
1220 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
1221 WHERE cc.parent=$parent
1222 $sort";
1223 } else {
1224 $parent = (int)$parent;
1225 $sql = "SELECT cc.*,
1226 ctx.id AS ctxid, ctx.path AS ctxpath,
1227 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1228 FROM {$CFG->prefix}course_categories cc
1229 JOIN {$CFG->prefix}context ctx
1230 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
1231 JOIN {$CFG->prefix}course_categories ccp
1232 ON (cc.path LIKE ".sql_concat('ccp.path',"'%'").")
1233 WHERE ccp.id=$parent
1234 $sort";
1236 $categories = array();
1238 if( $rs = get_recordset_sql($sql) ){
1239 while ($cat = rs_fetch_next_record($rs)) {
1240 $cat = make_context_subobj($cat);
1241 if ($cat->visible || has_capability('moodle/category:viewhiddencategories',$cat->context)) {
1242 $categories[$cat->id] = $cat;
1246 return $categories;
1251 * Returns an array of category ids of all the subcategories for a given
1252 * category.
1253 * @param $catid - The id of the category whose subcategories we want to find.
1254 * @return array of category ids.
1256 function get_all_subcategories($catid) {
1258 $subcats = array();
1260 if ($categories = get_records('course_categories', 'parent', $catid)) {
1261 foreach ($categories as $cat) {
1262 array_push($subcats, $cat->id);
1263 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
1266 return $subcats;
1271 * This recursive function makes sure that the courseorder is consecutive
1273 * @param type description
1275 * $n is the starting point, offered only for compatilibity -- will be ignored!
1276 * $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
1277 * safely from 1.4 to 1.5
1279 function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
1281 global $CFG;
1283 $count = 0;
1285 $catgap = 1000; // "standard" category gap
1286 $tolerance = 200; // how "close" categories can get
1288 if ($categoryid > 0){
1289 // update depth and path
1290 $cat = get_record('course_categories', 'id', $categoryid);
1291 if ($cat->parent == 0) {
1292 $depth = 0;
1293 $path = '';
1294 } else if ($depth == 0 ) { // doesn't make sense; get from DB
1295 // this is only called if the $depth parameter looks dodgy
1296 $parent = get_record('course_categories', 'id', $cat->parent);
1297 $path = $parent->path;
1298 $depth = $parent->depth;
1300 $path = $path . '/' . $categoryid;
1301 $depth = $depth + 1;
1303 if ($cat->path !== $path) {
1304 set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
1306 if ($cat->depth != $depth) {
1307 set_field('course_categories', 'depth', $depth, 'id', $categoryid);
1311 // get some basic info about courses in the category
1312 $info = get_record_sql('SELECT MIN(sortorder) AS min,
1313 MAX(sortorder) AS max,
1314 COUNT(sortorder) AS count
1315 FROM ' . $CFG->prefix . 'course
1316 WHERE category=' . $categoryid);
1317 if (is_object($info)) { // no courses?
1318 $max = $info->max;
1319 $count = $info->count;
1320 $min = $info->min;
1321 unset($info);
1324 if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
1325 $n = $min;
1328 // $hasgap flag indicates whether there's a gap in the sequence
1329 $hasgap = false;
1330 if ($max-$min+1 != $count) {
1331 $hasgap = true;
1334 // $mustshift indicates whether the sequence must be shifted to
1335 // meet its range
1336 $mustshift = false;
1337 if ($min < $n+$tolerance || $min > $n+$tolerance+$catgap ) {
1338 $mustshift = true;
1341 // actually sort only if there are courses,
1342 // and we meet one ofthe triggers:
1343 // - safe flag
1344 // - they are not in a continuos block
1345 // - they are too close to the 'bottom'
1346 if ($count && ( $safe || $hasgap || $mustshift ) ) {
1347 // special, optimized case where all we need is to shift
1348 if ( $mustshift && !$safe && !$hasgap) {
1349 $shift = $n + $catgap - $min;
1350 if ($shift < $count) {
1351 $shift = $count + $catgap;
1353 // UPDATE course SET sortorder=sortorder+$shift
1354 execute_sql("UPDATE {$CFG->prefix}course
1355 SET sortorder=sortorder+$shift
1356 WHERE category=$categoryid", 0);
1357 $n = $n + $catgap + $count;
1359 } else { // do it slowly
1360 $n = $n + $catgap;
1361 // if the new sequence overlaps the current sequence, lack of transactions
1362 // will stop us -- shift things aside for a moment...
1363 if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbfamily==='mysql')) {
1364 $shift = $max + $n + 1000;
1365 execute_sql("UPDATE {$CFG->prefix}course
1366 SET sortorder=sortorder+$shift
1367 WHERE category=$categoryid", 0);
1370 $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
1371 begin_sql();
1372 $tx = true; // transaction sanity
1373 foreach ($courses as $course) {
1374 if ($tx && $course->sortorder != $n ) { // save db traffic
1375 $tx = $tx && set_field('course', 'sortorder', $n,
1376 'id', $course->id);
1378 $n++;
1380 if ($tx) {
1381 commit_sql();
1382 } else {
1383 rollback_sql();
1384 if (!$safe) {
1385 // if we failed when called with !safe, try
1386 // to recover calling self with safe=true
1387 return fix_course_sortorder($categoryid, $n, true, $depth, $path);
1392 set_field('course_categories', 'coursecount', $count, 'id', $categoryid);
1394 // $n could need updating
1395 $max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid");
1396 if ($max > $n) {
1397 $n = $max;
1400 if ($categories = get_categories($categoryid)) {
1401 foreach ($categories as $category) {
1402 $n = fix_course_sortorder($category->id, $n, $safe, $depth, $path);
1406 return $n+1;
1410 * Ensure all courses have a valid course category
1411 * useful if a category has been removed manually
1413 function fix_coursecategory_orphans() {
1415 global $CFG;
1417 // Note: the handling of sortorder here is arguably
1418 // open to race conditions. Hard to fix here, unlikely
1419 // to hit anyone in production.
1421 $sql = "SELECT c.id, c.category, c.shortname
1422 FROM {$CFG->prefix}course c
1423 LEFT OUTER JOIN {$CFG->prefix}course_categories cc ON c.category=cc.id
1424 WHERE cc.id IS NULL AND c.id != " . SITEID;
1426 $rs = get_recordset_sql($sql);
1428 if (!rs_EOF($rs)) { // we have some orphans
1430 // the "default" category is the lowest numbered...
1431 $default = get_field_sql("SELECT MIN(id)
1432 FROM {$CFG->prefix}course_categories");
1433 $sortorder = get_field_sql("SELECT MAX(sortorder)
1434 FROM {$CFG->prefix}course
1435 WHERE category=$default");
1438 begin_sql();
1439 $tx = true;
1440 while ($tx && $course = rs_fetch_next_record($rs)) {
1441 $tx = $tx && set_field('course', 'category', $default, 'id', $course->id);
1442 $tx = $tx && set_field('course', 'sortorder', ++$sortorder, 'id', $course->id);
1444 if ($tx) {
1445 commit_sql();
1446 } else {
1447 rollback_sql();
1450 rs_close($rs);
1454 * List of remote courses that a user has access to via MNET.
1455 * Works only on the IDP
1457 * @uses $CFG, $USER
1458 * @return array {@link $COURSE} of course objects
1460 function get_my_remotecourses($userid=0) {
1461 global $CFG, $USER;
1463 if (empty($userid)) {
1464 $userid = $USER->id;
1467 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1468 c.hostid, c.summary, c.cat_name,
1469 h.name AS hostname
1470 FROM {$CFG->prefix}mnet_enrol_course c
1471 JOIN {$CFG->prefix}mnet_enrol_assignments a ON c.id=a.courseid
1472 JOIN {$CFG->prefix}mnet_host h ON c.hostid=h.id
1473 WHERE a.userid={$userid}";
1475 return get_records_sql($sql);
1479 * List of remote hosts that a user has access to via MNET.
1480 * Works on the SP
1482 * @uses $CFG, $USER
1483 * @return array of host objects
1485 function get_my_remotehosts() {
1486 global $CFG, $USER;
1488 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1489 return false; // Return nothing on the IDP
1491 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1492 return $USER->mnet_foreign_host_array;
1494 return false;
1498 * This function creates a default separated/connected scale
1500 * This function creates a default separated/connected scale
1501 * so there's something in the database. The locations of
1502 * strings and files is a bit odd, but this is because we
1503 * need to maintain backward compatibility with many different
1504 * existing language translations and older sites.
1506 * @uses $CFG
1508 function make_default_scale() {
1510 global $CFG;
1512 $defaultscale = NULL;
1513 $defaultscale->courseid = 0;
1514 $defaultscale->userid = 0;
1515 $defaultscale->name = get_string('separateandconnected');
1516 $defaultscale->scale = get_string('postrating1', 'forum').','.
1517 get_string('postrating2', 'forum').','.
1518 get_string('postrating3', 'forum');
1519 $defaultscale->timemodified = time();
1521 /// Read in the big description from the file. Note this is not
1522 /// HTML (despite the file extension) but Moodle format text.
1523 $parentlang = get_string('parentlanguage');
1524 if ($parentlang[0] == '[') {
1525 $parentlang = '';
1527 if (is_readable($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1528 $file = file($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1529 } else if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1530 $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1531 } else if ($parentlang and is_readable($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1532 $file = file($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
1533 } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1534 $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
1535 } else if (is_readable($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html')) {
1536 $file = file($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html');
1537 } else {
1538 $file = '';
1541 $defaultscale->description = addslashes(implode('', $file));
1543 if ($defaultscale->id = insert_record('scale', $defaultscale)) {
1544 execute_sql('UPDATE '. $CFG->prefix .'forum SET scale = \''. $defaultscale->id .'\'', false);
1550 * Returns a menu of all available scales from the site as well as the given course
1552 * @uses $CFG
1553 * @param int $courseid The id of the course as found in the 'course' table.
1554 * @return object
1556 function get_scales_menu($courseid=0) {
1558 global $CFG;
1560 $sql = "SELECT id, name FROM {$CFG->prefix}scale
1561 WHERE courseid = '0' or courseid = '$courseid'
1562 ORDER BY courseid ASC, name ASC";
1564 if ($scales = get_records_sql_menu($sql)) {
1565 return $scales;
1568 make_default_scale();
1570 return get_records_sql_menu($sql);
1576 * Given a set of timezone records, put them in the database, replacing what is there
1578 * @uses $CFG
1579 * @param array $timezones An array of timezone records
1581 function update_timezone_records($timezones) {
1582 /// Given a set of timezone records, put them in the database
1584 global $CFG;
1586 /// Clear out all the old stuff
1587 execute_sql('TRUNCATE TABLE '.$CFG->prefix.'timezone', false);
1589 /// Insert all the new stuff
1590 foreach ($timezones as $timezone) {
1591 if (is_array($timezone)) {
1592 $timezone = (object)$timezone;
1594 insert_record('timezone', $timezone);
1599 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1602 * Just gets a raw list of all modules in a course
1604 * @uses $CFG
1605 * @param int $courseid The id of the course as found in the 'course' table.
1606 * @return object
1608 function get_course_mods($courseid) {
1609 global $CFG;
1611 if (empty($courseid)) {
1612 return false; // avoid warnings
1615 return get_records_sql("SELECT cm.*, m.name as modname
1616 FROM {$CFG->prefix}modules m,
1617 {$CFG->prefix}course_modules cm
1618 WHERE cm.course = ".intval($courseid)."
1619 AND cm.module = m.id AND m.visible = 1"); // no disabled mods
1624 * Given an id of a course module, finds the coursemodule description
1626 * @param string $modulename name of module type, eg. resource, assignment,...
1627 * @param int $cmid course module id (id in course_modules table)
1628 * @param int $courseid optional course id for extra validation
1629 * @return object course module instance with instance and module name
1631 function get_coursemodule_from_id($modulename, $cmid, $courseid=0) {
1633 global $CFG;
1635 $courseselect = ($courseid) ? 'cm.course = '.intval($courseid).' AND ' : '';
1637 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1638 FROM {$CFG->prefix}course_modules cm,
1639 {$CFG->prefix}modules md,
1640 {$CFG->prefix}$modulename m
1641 WHERE $courseselect
1642 cm.id = ".intval($cmid)." AND
1643 cm.instance = m.id AND
1644 md.name = '$modulename' AND
1645 md.id = cm.module");
1649 * Given an instance number of a module, finds the coursemodule description
1651 * @param string $modulename name of module type, eg. resource, assignment,...
1652 * @param int $instance module instance number (id in resource, assignment etc. table)
1653 * @param int $courseid optional course id for extra validation
1654 * @return object course module instance with instance and module name
1656 function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
1658 global $CFG;
1660 $courseselect = ($courseid) ? 'cm.course = '.intval($courseid).' AND ' : '';
1662 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1663 FROM {$CFG->prefix}course_modules cm,
1664 {$CFG->prefix}modules md,
1665 {$CFG->prefix}$modulename m
1666 WHERE $courseselect
1667 cm.instance = m.id AND
1668 md.name = '$modulename' AND
1669 md.id = cm.module AND
1670 m.id = ".intval($instance));
1675 * Returns all course modules of given activity in course
1676 * @param string $modulename (forum, quiz, etc.)
1677 * @param int $courseid
1678 * @param string $extrafields extra fields starting with m.
1679 * @return array of cm objects, false if not found or error
1681 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1682 global $CFG;
1684 if (!empty($extrafields)) {
1685 $extrafields = ", $extrafields";
1687 return get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1688 FROM {$CFG->prefix}course_modules cm,
1689 {$CFG->prefix}modules md,
1690 {$CFG->prefix}$modulename m
1691 WHERE cm.course = $courseid AND
1692 cm.instance = m.id AND
1693 md.name = '$modulename' AND
1694 md.id = cm.module");
1698 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1700 * Returns an array of all the active instances of a particular
1701 * module in given courses, sorted in the order they are defined
1702 * in the course. Returns an empty array on any errors.
1704 * The returned objects includle the columns cw.section, cm.visible,
1705 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1707 * @param string $modulename The name of the module to get instances for
1708 * @param array $courses an array of course objects.
1709 * @return array of module instance objects, including some extra fields from the course_modules
1710 * and course_sections tables, or an empty array if an error occurred.
1712 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1713 global $CFG;
1715 $outputarray = array();
1717 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1718 return $outputarray;
1721 if (!$rawmods = get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1722 cm.groupmode, cm.groupingid, cm.groupmembersonly
1723 FROM {$CFG->prefix}course_modules cm,
1724 {$CFG->prefix}course_sections cw,
1725 {$CFG->prefix}modules md,
1726 {$CFG->prefix}$modulename m
1727 WHERE cm.course IN (".implode(',',array_keys($courses)).") AND
1728 cm.instance = m.id AND
1729 cm.section = cw.id AND
1730 md.name = '$modulename' AND
1731 md.id = cm.module")) {
1732 return $outputarray;
1735 require_once($CFG->dirroot.'/course/lib.php');
1737 foreach ($courses as $course) {
1738 $modinfo = get_fast_modinfo($course, $userid);
1740 if (empty($modinfo->instances[$modulename])) {
1741 continue;
1744 foreach ($modinfo->instances[$modulename] as $cm) {
1745 if (!$includeinvisible and !$cm->uservisible) {
1746 continue;
1748 if (!isset($rawmods[$cm->id])) {
1749 continue;
1751 $instance = $rawmods[$cm->id];
1752 if (!empty($cm->extra)) {
1753 $instance->extra = urlencode($cm->extra); // bc compatibility
1755 $outputarray[] = $instance;
1759 return $outputarray;
1763 * Returns an array of all the active instances of a particular module in a given course,
1764 * sorted in the order they are defined.
1766 * Returns an array of all the active instances of a particular
1767 * module in a given course, sorted in the order they are defined
1768 * in the course. Returns an empty array on any errors.
1770 * The returned objects includle the columns cw.section, cm.visible,
1771 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1773 * @param string $modulename The name of the module to get instances for
1774 * @param object $course The course obect.
1775 * @return array of module instance objects, including some extra fields from the course_modules
1776 * and course_sections tables, or an empty array if an error occurred.
1778 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1779 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1784 * Determine whether a module instance is visible within a course
1786 * Given a valid module object with info about the id and course,
1787 * and the module's type (eg "forum") returns whether the object
1788 * is visible or not, groupmembersonly visibility not tested
1790 * @uses $CFG
1791 * @param $moduletype Name of the module eg 'forum'
1792 * @param $module Object which is the instance of the module
1793 * @return bool
1795 function instance_is_visible($moduletype, $module) {
1797 global $CFG;
1799 if (!empty($module->id)) {
1800 if ($records = get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1801 FROM {$CFG->prefix}course_modules cm,
1802 {$CFG->prefix}modules m
1803 WHERE cm.course = '$module->course' AND
1804 cm.module = m.id AND
1805 m.name = '$moduletype' AND
1806 cm.instance = '$module->id'")) {
1808 foreach ($records as $record) { // there should only be one - use the first one
1809 return $record->visible;
1813 return true; // visible by default!
1817 * Determine whether a course module is visible within a course,
1818 * this is different from instance_is_visible() - faster and visibility for user
1820 * @param object $cm object
1821 * @param int $userid empty means current user
1822 * @return bool
1824 function coursemodule_visible_for_user($cm, $userid=0) {
1825 global $USER;
1827 if (empty($cm->id)) {
1828 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1829 return false;
1831 if (empty($userid)) {
1832 $userid = $USER->id;
1834 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1835 return false;
1837 return groups_course_module_visible($cm, $userid);
1843 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1847 * Add an entry to the log table.
1849 * Add an entry to the log table. These are "action" focussed rather
1850 * than web server hits, and provide a way to easily reconstruct what
1851 * any particular student has been doing.
1853 * @uses $CFG
1854 * @uses $USER
1855 * @uses $db
1856 * @uses $REMOTE_ADDR
1857 * @uses SITEID
1858 * @param int $courseid The course id
1859 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
1860 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1861 * @param string $url The file and parameters used to see the results of the action
1862 * @param string $info Additional description information
1863 * @param string $cm The course_module->id if there is one
1864 * @param string $user If log regards $user other than $USER
1866 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1867 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1868 // This is for a good reason: it is the most frequently used DB update function,
1869 // so it has been optimised for speed.
1870 global $db, $CFG, $USER;
1872 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
1873 $cm = 0;
1876 if ($user) {
1877 $userid = $user;
1878 } else {
1879 if (!empty($USER->realuser)) { // Don't log
1880 return;
1882 $userid = empty($USER->id) ? '0' : $USER->id;
1885 $REMOTE_ADDR = getremoteaddr();
1886 if (empty($REMOTE_ADDR)) {
1887 $REMOTE_ADDR = '0.0.0.0';
1890 $timenow = time();
1891 $info = addslashes($info);
1892 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1893 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
1896 // Restrict length of log lines to the space actually available in the
1897 // database so that it doesn't cause a DB error. Log a warning so that
1898 // developers can avoid doing things which are likely to cause this on a
1899 // routine basis.
1900 $tl=textlib_get_instance();
1901 if(!empty($info) && $tl->strlen($info)>255) {
1902 $info=$tl->substr($info,0,252).'...';
1903 debugging('Warning: logged very long info',DEBUG_DEVELOPER);
1905 // Note: Unlike $info, URL appears to be already slashed before this function
1906 // is called. Since database limits are for the data before slashes, we need
1907 // to remove them...
1908 $url=stripslashes($url);
1909 // If the 100 field size is changed, also need to alter print_log in course/lib.php
1910 if(!empty($url) && $tl->strlen($url)>100) {
1911 $url=$tl->substr($url,0,97).'...';
1912 debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
1914 $url=addslashes($url);
1916 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; $PERF->logwrites++;};
1918 if ($CFG->type = 'oci8po') {
1919 if (empty($info)) {
1920 $info = ' ';
1923 $sql ='INSERT INTO '. $CFG->prefix .'log (time, userid, course, ip, module, cmid, action, url, info)
1924 VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')";
1926 $result = $db->Execute($sql);
1928 // MDL-11893, alert $CFG->supportemail if insert into log failed
1929 if (!$result && $CFG->supportemail) {
1930 $site = get_site();
1931 $subject = 'Insert into log failed at your moodle site '.$site->fullname;
1932 $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";
1933 $message .= "The failed SQL is:\n\n" . $sql;
1935 // email_to_user is not usable because email_to_user tries to write to the logs table,
1936 // and this will get caught in an infinite loop, if disk is full
1937 if (empty($CFG->noemailever)) {
1938 $lasttime = get_config('admin', 'lastloginserterrormail');
1939 if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
1940 mail($CFG->supportemail, $subject, $message);
1941 set_config('lastloginserterrormail', time(), 'admin');
1946 if (!$result) {
1947 debugging('Error: Could not insert a new entry to the Moodle log', DEBUG_ALL);
1953 * Store user last access times - called when use enters a course or site
1955 * Note: we use ADOdb code directly in this function to save some CPU
1956 * cycles here and there. They are simple operations not needing any
1957 * of the postprocessing performed by dmllib.php
1959 * @param int $courseid, empty means site
1960 * @return void
1962 function user_accesstime_log($courseid=0) {
1964 global $USER, $CFG, $PERF, $db;
1966 if (!isloggedin() or !empty($USER->realuser)) {
1967 // no access tracking
1968 return;
1971 if (empty($courseid)) {
1972 $courseid = SITEID;
1975 $timenow = time();
1977 /// Store site lastaccess time for the current user
1978 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1979 /// Update $USER->lastaccess for next checks
1980 $USER->lastaccess = $timenow;
1981 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
1983 $remoteaddr = getremoteaddr();
1984 if ($db->Execute("UPDATE {$CFG->prefix}user
1985 SET lastip = '$remoteaddr', lastaccess = $timenow
1986 WHERE id = $USER->id")) {
1987 } else {
1988 debugging('Error: Could not update global user lastaccess information'); // Don't throw an error
1990 /// Remove this record from record cache since it will change
1991 if (!empty($CFG->rcache)) {
1992 rcache_unset('user', $USER->id);
1996 if ($courseid == SITEID) {
1997 /// no user_lastaccess for frontpage
1998 return;
2001 /// Store course lastaccess times for the current user
2002 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
2003 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
2005 $exists = false; // To detect if the user_lastaccess record exists or no
2006 if ($rs = $db->Execute("SELECT timeaccess
2007 FROM {$CFG->prefix}user_lastaccess
2008 WHERE userid = $USER->id AND courseid = $courseid")) {
2009 if (!$rs->EOF) {
2010 $exists = true;
2011 $lastaccess = reset($rs->fields);
2012 if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
2013 /// no need to update now, it was updated recently in concurrent login ;-)
2014 $rs->Close();
2015 return;
2018 $rs->Close();
2021 /// Update course lastaccess for next checks
2022 $USER->currentcourseaccess[$courseid] = $timenow;
2023 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
2025 if ($exists) { // user_lastaccess record exists, update it
2026 if ($db->Execute("UPDATE {$CFG->prefix}user_lastaccess
2027 SET timeaccess = $timenow
2028 WHERE userid = $USER->id AND courseid = $courseid")) {
2029 } else {
2030 debugging('Error: Could not update course user lastacess information'); // Don't throw an error
2033 } else { // user lastaccess record doesn't exist, insert it
2034 if ($db->Execute("INSERT INTO {$CFG->prefix}user_lastaccess
2035 (userid, courseid, timeaccess)
2036 VALUES ($USER->id, $courseid, $timenow)")) {
2037 } else {
2038 debugging('Error: Could not insert course user lastaccess information'); // Don't throw an error
2045 * Select all log records based on SQL criteria
2047 * @uses $CFG
2048 * @param string $select SQL select criteria
2049 * @param string $order SQL order by clause to sort the records returned
2050 * @param string $limitfrom ?
2051 * @param int $limitnum ?
2052 * @param int $totalcount Passed in by reference.
2053 * @return object
2054 * @todo Finish documenting this function
2056 function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
2057 global $CFG;
2059 if ($order) {
2060 $order = 'ORDER BY '. $order;
2063 $selectsql = $CFG->prefix .'log l LEFT JOIN '. $CFG->prefix .'user u ON l.userid = u.id '. ((strlen($select) > 0) ? 'WHERE '. $select : '');
2064 $countsql = $CFG->prefix.'log l '.((strlen($select) > 0) ? ' WHERE '. $select : '');
2066 $totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql");
2068 return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture
2069 FROM '. $selectsql .' '. $order, $limitfrom, $limitnum) ;
2074 * Select all log records for a given course and user
2076 * @uses $CFG
2077 * @uses DAYSECS
2078 * @param int $userid The id of the user as found in the 'user' table.
2079 * @param int $courseid The id of the course as found in the 'course' table.
2080 * @param string $coursestart ?
2081 * @todo Finish documenting this function
2083 function get_logs_usercourse($userid, $courseid, $coursestart) {
2084 global $CFG;
2086 if ($courseid) {
2087 $courseselect = ' AND course = \''. $courseid .'\' ';
2088 } else {
2089 $courseselect = '';
2092 return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS .") as day, count(*) as num
2093 FROM {$CFG->prefix}log
2094 WHERE userid = '$userid'
2095 AND time > '$coursestart' $courseselect
2096 GROUP BY floor((time - $coursestart)/". DAYSECS .") ");
2100 * Select all log records for a given course, user, and day
2102 * @uses $CFG
2103 * @uses HOURSECS
2104 * @param int $userid The id of the user as found in the 'user' table.
2105 * @param int $courseid The id of the course as found in the 'course' table.
2106 * @param string $daystart ?
2107 * @return object
2108 * @todo Finish documenting this function
2110 function get_logs_userday($userid, $courseid, $daystart) {
2111 global $CFG;
2113 if ($courseid) {
2114 $courseselect = ' AND course = \''. $courseid .'\' ';
2115 } else {
2116 $courseselect = '';
2119 return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS .") as hour, count(*) as num
2120 FROM {$CFG->prefix}log
2121 WHERE userid = '$userid'
2122 AND time > '$daystart' $courseselect
2123 GROUP BY floor((time - $daystart)/". HOURSECS .") ");
2127 * Returns an object with counts of failed login attempts
2129 * Returns information about failed login attempts. If the current user is
2130 * an admin, then two numbers are returned: the number of attempts and the
2131 * number of accounts. For non-admins, only the attempts on the given user
2132 * are shown.
2134 * @param string $mode Either 'admin', 'teacher' or 'everybody'
2135 * @param string $username The username we are searching for
2136 * @param string $lastlogin The date from which we are searching
2137 * @return int
2139 function count_login_failures($mode, $username, $lastlogin) {
2141 $select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin;
2143 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Return information about all accounts
2144 if ($count->attempts = count_records_select('log', $select)) {
2145 $count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)');
2146 return $count;
2148 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
2149 if ($count->attempts = count_records_select('log', $select .' AND info = \''. $username .'\'')) {
2150 return $count;
2153 return NULL;
2157 /// GENERAL HELPFUL THINGS ///////////////////////////////////
2160 * Dump a given object's information in a PRE block.
2162 * Mostly just used for debugging.
2164 * @param mixed $object The data to be printed
2166 function print_object($object) {
2167 echo '<pre class="notifytiny">' . htmlspecialchars(print_r($object,true)) . '</pre>';
2171 * Check whether a course is visible through its parents
2172 * path.
2174 * Notes:
2176 * - All we need from the course is ->category. _However_
2177 * if the course object has a categorypath property,
2178 * we'll save a dbquery
2180 * - If we return false, you'll still need to check if
2181 * the user can has the 'moodle/category:viewhiddencategories'
2182 * capability...
2184 * - Will generate 2 DB calls.
2186 * - It does have a small local cache, however...
2188 * - Do NOT call this over many courses as it'll generate
2189 * DB traffic. Instead, see what get_my_courses() does.
2191 * @param mixed $object A course object
2192 * @return bool
2194 function course_parent_visible($course = null) {
2195 global $CFG;
2196 //return true;
2197 static $mycache;
2199 if (!is_object($course)) {
2200 return true;
2202 if (!empty($CFG->allowvisiblecoursesinhiddencategories)) {
2203 return true;
2206 if (!isset($mycache)) {
2207 $mycache = array();
2208 } else {
2209 // cast to force assoc array
2210 $k = (string)$course->category;
2211 if (isset($mycache[$k])) {
2212 return $mycache[$k];
2216 if (isset($course->categorypath)) {
2217 $path = $course->categorypath;
2218 } else {
2219 $path = get_field('course_categories', 'path',
2220 'id', $course->category);
2222 $catids = substr($path,1); // strip leading slash
2223 $catids = str_replace('/',',',$catids);
2225 $sql = "SELECT MIN(visible)
2226 FROM {$CFG->prefix}course_categories
2227 WHERE id IN ($catids)";
2228 $vis = get_field_sql($sql);
2230 // cast to force assoc array
2231 $k = (string)$course->category;
2232 $mycache[$k] = $vis;
2234 return $vis;
2238 * This function is the official hook inside XMLDB stuff to delegate its debug to one
2239 * external function.
2241 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
2242 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
2244 * @param $message string contains the error message
2245 * @param $object object XMLDB object that fired the debug
2247 function xmldb_debug($message, $object) {
2249 debugging($message, DEBUG_DEVELOPER);
2253 * true or false function to see if user can create any courses at all
2254 * @return bool
2256 function user_can_create_courses() {
2257 global $USER;
2258 // if user has course creation capability at any site or course cat, then return true;
2260 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
2261 return true;
2263 if ($cats = get_records('course_categories')) {
2264 foreach ($cats as $cat) {
2265 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) {
2266 return true;
2270 return false;
2273 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: