Merge branch 'MDL-23872_m19' of git://github.com/nebgor/moodle into MOODLE_19_STABLE
[moodle.git] / lib / datalib.php
blob2a96bae76be5468782fca7c081182c2ac4981d21
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 () {
45 static $myadmin;
47 if (! isset($admin)) {
48 if (! $admins = get_admins()) {
49 return false;
51 $admin = reset($admins);//reset returns first element
53 return $admin;
56 /**
57 * Returns list of all admins, using 1 DB query. It depends on DB schema v1.7
58 * but does not depend on the v1.9 datastructures (context.path, etc).
60 * @uses $CFG
61 * @return object
63 function get_admins() {
65 global $CFG;
67 $sql = "SELECT ra.userid, SUM(rc.permission) AS permission, MIN(ra.id) AS adminid
68 FROM " . $CFG->prefix . "role_capabilities rc
69 JOIN " . $CFG->prefix . "context ctx
70 ON ctx.id=rc.contextid
71 JOIN " . $CFG->prefix . "role_assignments ra
72 ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
73 WHERE ctx.contextlevel=10
74 AND rc.capability IN ('moodle/site:config',
75 'moodle/legacy:admin',
76 'moodle/site:doanything')
77 GROUP BY ra.userid
78 HAVING SUM(rc.permission) > 0";
80 $sql = "SELECT u.*, ra.adminid
81 FROM " . $CFG->prefix . "user u
82 JOIN ($sql) ra
83 ON u.id=ra.userid
84 ORDER BY ra.adminid ASC";
86 return get_records_sql($sql);
90 function get_courses_in_metacourse($metacourseid) {
91 global $CFG;
93 $sql = "SELECT c.id,c.shortname,c.fullname FROM {$CFG->prefix}course c, {$CFG->prefix}course_meta mc WHERE mc.parent_course = $metacourseid
94 AND mc.child_course = c.id ORDER BY c.shortname";
96 return get_records_sql($sql);
99 function get_courses_notin_metacourse($metacourseid,$count=false) {
101 global $CFG;
103 if ($count) {
104 $sql = "SELECT COUNT(c.id)";
105 } else {
106 $sql = "SELECT c.id,c.shortname,c.fullname";
109 $alreadycourses = get_courses_in_metacourse($metacourseid);
111 $sql .= " FROM {$CFG->prefix}course c WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
112 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1 ".((empty($count)) ? " ORDER BY c.shortname" : "");
114 return get_records_sql($sql);
117 function count_courses_notin_metacourse($metacourseid) {
118 global $CFG;
120 $alreadycourses = get_courses_in_metacourse($metacourseid);
122 $sql = "SELECT COUNT(c.id) AS notin FROM {$CFG->prefix}course c
123 WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
124 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1";
126 if (!$count = get_record_sql($sql)) {
127 return 0;
130 return $count->notin;
134 * Search through course users
136 * If $coursid specifies the site course then this function searches
137 * through all undeleted and confirmed users
139 * @uses $CFG
140 * @uses SITEID
141 * @param int $courseid The course in question.
142 * @param int $groupid The group in question.
143 * @param string $searchtext ?
144 * @param string $sort ?
145 * @param string $exceptions ?
146 * @return object
148 function search_users($courseid, $groupid, $searchtext, $sort='', $exceptions='') {
149 global $CFG;
151 $LIKE = sql_ilike();
152 $fullname = sql_fullname('u.firstname', 'u.lastname');
154 if (!empty($exceptions)) {
155 $except = ' AND u.id NOT IN ('. $exceptions .') ';
156 } else {
157 $except = '';
160 if (!empty($sort)) {
161 $order = ' ORDER BY '. $sort;
162 } else {
163 $order = '';
166 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
168 if (!$courseid or $courseid == SITEID) {
169 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
170 FROM {$CFG->prefix}user u
171 WHERE $select
172 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
173 $except $order");
174 } else {
176 if ($groupid) {
177 //TODO:check. Remove group DB dependencies.
178 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
179 FROM {$CFG->prefix}user u,
180 {$CFG->prefix}groups_members gm
181 WHERE $select AND gm.groupid = '$groupid' AND gm.userid = u.id
182 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
183 $except $order");
184 } else {
185 $context = get_context_instance(CONTEXT_COURSE, $courseid);
186 $contextlists = get_related_contexts_string($context);
187 $users = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
188 FROM {$CFG->prefix}user u,
189 {$CFG->prefix}role_assignments ra
190 WHERE $select AND ra.contextid $contextlists AND ra.userid = u.id
191 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
192 $except $order");
194 return $users;
200 * Returns a list of all site users
201 * Obsolete, just calls get_course_users(SITEID)
203 * @uses SITEID
204 * @deprecated Use {@link get_course_users()} instead.
205 * @param string $fields A comma separated list of fields to be returned from the chosen table.
206 * @param string $exceptions A comma separated list of user->id to be skiped in the result returned by the function
207 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
208 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
209 * @return object|false {@link $USER} records or false if error.
211 function get_site_users($sort='u.lastaccess DESC', $fields='*', $exceptions='', $limitfrom='', $limitnum='') {
213 return get_course_users(SITEID, $sort, $exceptions, $fields, $limitfrom, $limitnum);
218 * Returns a subset of users
220 * @uses $CFG
221 * @param bool $get If false then only a count of the records is returned
222 * @param string $search A simple string to search for
223 * @param bool $confirmed A switch to allow/disallow unconfirmed users
224 * @param array(int) $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
225 * @param string $sort A SQL snippet for the sorting criteria to use
226 * @param string $firstinitial ?
227 * @param string $lastinitial ?
228 * @param string $page ?
229 * @param string $recordsperpage ?
230 * @param string $fields A comma separated list of fields to be returned from the chosen table.
231 * @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.
233 function get_users($get=true, $search='', $confirmed=false, $exceptions='', $sort='firstname ASC',
234 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='') {
236 global $CFG;
238 if ($get && !$recordsperpage) {
239 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
240 'On large installations, this will probably cause an out of memory error. ' .
241 'Please think again and change your code so that it does not try to ' .
242 'load so much data into memory.', DEBUG_DEVELOPER);
245 $LIKE = sql_ilike();
246 $fullname = sql_fullname();
248 $select = 'username <> \'guest\' AND deleted = 0';
250 if (!empty($search)){
251 $search = trim($search);
252 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
255 if ($confirmed) {
256 $select .= ' AND confirmed = \'1\' ';
259 if ($exceptions) {
260 $select .= ' AND id NOT IN ('. $exceptions .') ';
263 if ($firstinitial) {
264 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\'';
266 if ($lastinitial) {
267 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\'';
270 if ($extraselect) {
271 $select .= " AND $extraselect ";
274 if ($get) {
275 return get_records_select('user', $select, $sort, $fields, $page, $recordsperpage);
276 } else {
277 return count_records_select('user', $select);
283 * shortdesc (optional)
285 * longdesc
287 * @uses $CFG
288 * @param string $sort ?
289 * @param string $dir ?
290 * @param int $categoryid ?
291 * @param int $categoryid ?
292 * @param string $search ?
293 * @param string $firstinitial ?
294 * @param string $lastinitial ?
295 * @returnobject {@link $USER} records
296 * @todo Finish documenting this function
299 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
300 $search='', $firstinitial='', $lastinitial='', $extraselect='') {
302 global $CFG;
304 $LIKE = sql_ilike();
305 $fullname = sql_fullname();
307 $select = "deleted <> '1'";
309 if (!empty($search)) {
310 $search = trim($search);
311 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%' OR username='$search') ";
314 if ($firstinitial) {
315 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\' ';
318 if ($lastinitial) {
319 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\' ';
322 if ($extraselect) {
323 $select .= " AND $extraselect ";
326 if ($sort) {
327 $sort = ' ORDER BY '. $sort .' '. $dir;
330 /// warning: will return UNCONFIRMED USERS
331 return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
332 FROM {$CFG->prefix}user
333 WHERE $select $sort", $page, $recordsperpage);
339 * Full list of users that have confirmed their accounts.
341 * @uses $CFG
342 * @return object
344 function get_users_confirmed() {
345 global $CFG;
346 return get_records_sql("SELECT *
347 FROM {$CFG->prefix}user
348 WHERE confirmed = 1
349 AND deleted = 0
350 AND username <> 'guest'");
354 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
358 * Returns $course object of the top-level site.
360 * @return course A {@link $COURSE} object for the site
362 function get_site() {
364 global $SITE;
366 if (!empty($SITE->id)) { // We already have a global to use, so return that
367 return $SITE;
370 if ($course = get_record('course', 'category', 0)) {
371 return $course;
372 } else {
373 return false;
378 * Returns list of courses, for whole site, or category
380 * Returns list of courses, for whole site, or category
381 * Important: Using c.* for fields is extremely expensive because
382 * we are using distinct. You almost _NEVER_ need all the fields
383 * in such a large SELECT
385 * @param type description
388 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
390 global $USER, $CFG;
392 if ($categoryid != "all" && is_numeric($categoryid)) {
393 $categoryselect = "WHERE c.category = '$categoryid'";
394 } else {
395 $categoryselect = "";
398 if (empty($sort)) {
399 $sortstatement = "";
400 } else {
401 $sortstatement = "ORDER BY $sort";
404 $visiblecourses = array();
406 // pull out all course matching the cat
407 if ($courses = get_records_sql("SELECT $fields,
408 ctx.id AS ctxid, ctx.path AS ctxpath,
409 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
410 FROM {$CFG->prefix}course c
411 JOIN {$CFG->prefix}context ctx
412 ON (c.id = ctx.instanceid
413 AND ctx.contextlevel=".CONTEXT_COURSE.")
414 $categoryselect
415 $sortstatement")) {
417 // loop throught them
418 foreach ($courses as $course) {
419 $course = make_context_subobj($course);
420 if (isset($course->visible) && $course->visible <= 0) {
421 // for hidden courses, require visibility check
422 if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
423 $visiblecourses [] = $course;
425 } else {
426 $visiblecourses [] = $course;
430 return $visiblecourses;
433 $teachertable = "";
434 $visiblecourses = "";
435 $sqland = "";
436 if (!empty($categoryselect)) {
437 $sqland = "AND ";
439 if (!empty($USER->id)) { // May need to check they are a teacher
440 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
441 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
442 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course = c.id";
444 } else {
445 $visiblecourses = "$sqland c.visible > 0";
448 if ($categoryselect or $visiblecourses) {
449 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
450 } else {
451 $selectsql = "{$CFG->prefix}course c $teachertable";
454 $extrafield = str_replace('ASC','',$sort);
455 $extrafield = str_replace('DESC','',$extrafield);
456 $extrafield = trim($extrafield);
457 if (!empty($extrafield)) {
458 $extrafield = ','.$extrafield;
460 return get_records_sql("SELECT ".((!empty($teachertable)) ? " DISTINCT " : "")." $fields $extrafield FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : ""));
466 * Returns list of courses, for whole site, or category
468 * Similar to get_courses, but allows paging
469 * Important: Using c.* for fields is extremely expensive because
470 * we are using distinct. You almost _NEVER_ need all the fields
471 * in such a large SELECT
473 * @param type description
476 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
477 &$totalcount, $limitfrom="", $limitnum="") {
479 global $USER, $CFG;
481 $categoryselect = "";
482 if ($categoryid != "all" && is_numeric($categoryid)) {
483 $categoryselect = "WHERE c.category = '$categoryid'";
484 } else {
485 $categoryselect = "";
488 // pull out all course matching the cat
489 $visiblecourses = array();
490 if (!($rs = get_recordset_sql("SELECT $fields,
491 ctx.id AS ctxid, ctx.path AS ctxpath,
492 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
493 FROM {$CFG->prefix}course c
494 JOIN {$CFG->prefix}context ctx
495 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
496 $categoryselect
497 ORDER BY $sort"))) {
498 return $visiblecourses;
500 $totalcount = 0;
502 if (!$limitfrom) {
503 $limitfrom = 0;
506 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
507 while ($course = rs_fetch_next_record($rs)) {
508 $course = make_context_subobj($course);
509 if ($course->visible <= 0) {
510 // for hidden courses, require visibility check
511 if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
512 $totalcount++;
513 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
514 $visiblecourses [] = $course;
517 } else {
518 $totalcount++;
519 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
520 $visiblecourses [] = $course;
524 rs_close($rs);
525 return $visiblecourses;
529 $categoryselect = "";
530 if ($categoryid != "all" && is_numeric($categoryid)) {
531 $categoryselect = "c.category = '$categoryid'";
534 $teachertable = "";
535 $visiblecourses = "";
536 $sqland = "";
537 if (!empty($categoryselect)) {
538 $sqland = "AND ";
540 if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
541 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
542 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
543 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
545 } else {
546 $visiblecourses = "$sqland c.visible > 0";
549 if ($limitfrom !== "") {
550 $limit = sql_paging_limit($limitfrom, $limitnum);
551 } else {
552 $limit = "";
555 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
557 $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
559 return get_records_sql("SELECT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
564 * Retrieve course records with the course managers and other related records
565 * that we need for print_course(). This allows print_courses() to do its job
566 * in a constant number of DB queries, regardless of the number of courses,
567 * role assignments, etc.
569 * The returned array is indexed on c.id, and each course will have
570 * - $course->context - a context obj
571 * - $course->managers - array containing RA objects that include a $user obj
572 * with the minimal fields needed for fullname()
575 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
577 * The plan is to
579 * - Grab the courses JOINed w/context
581 * - Grab the interesting course-manager RAs
582 * JOINed with a base user obj and add them to each course
584 * So as to do all the work in 2 DB queries. The RA+user JOIN
585 * ends up being pretty expensive if it happens over _all_
586 * courses on a large site. (Are we surprised!?)
588 * So this should _never_ get called with 'all' on a large site.
591 global $USER, $CFG;
593 $allcats = false; // bool flag
594 if ($categoryid === 'all') {
595 $categoryclause = '';
596 $allcats = true;
597 } elseif (is_numeric($categoryid)) {
598 $categoryclause = "c.category = $categoryid";
599 } else {
600 debugging("Could not recognise categoryid = $categoryid");
601 $categoryclause = '';
604 $basefields = array('id', 'category', 'sortorder',
605 'shortname', 'fullname', 'idnumber',
606 'teacher', 'teachers', 'student', 'students',
607 'guest', 'startdate', 'visible',
608 'newsitems', 'cost', 'enrol',
609 'groupmode', 'groupmodeforce');
611 if (!is_null($fields) && is_string($fields)) {
612 if (empty($fields)) {
613 $fields = $basefields;
614 } else {
615 // turn the fields from a string to an array that
616 // get_user_courses_bycap() will like...
617 $fields = explode(',',$fields);
618 $fields = array_map('trim', $fields);
619 $fields = array_unique(array_merge($basefields, $fields));
621 } elseif (is_array($fields)) {
622 $fields = array_merge($basefields,$fields);
624 $coursefields = 'c.' .join(',c.', $fields);
626 if (empty($sort)) {
627 $sortstatement = "";
628 } else {
629 $sortstatement = "ORDER BY $sort";
632 $where = 'WHERE c.id != ' . SITEID;
633 if ($categoryclause !== ''){
634 $where = "$where AND $categoryclause";
637 // pull out all courses matching the cat
638 $sql = "SELECT $coursefields,
639 ctx.id AS ctxid, ctx.path AS ctxpath,
640 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
641 FROM {$CFG->prefix}course c
642 JOIN {$CFG->prefix}context ctx
643 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
644 $where
645 $sortstatement";
647 $catpaths = array();
648 $catpath = NULL;
649 if ($courses = get_records_sql($sql)) {
650 // loop on courses materialising
651 // the context, and prepping data to fetch the
652 // managers efficiently later...
653 foreach ($courses as $k => $course) {
654 $courses[$k] = make_context_subobj($courses[$k]);
655 $courses[$k]->managers = array();
656 if ($allcats === false) {
657 // single cat, so take just the first one...
658 if ($catpath === NULL) {
659 $catpath = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
661 } else {
662 // chop off the contextid of the course itself
663 // like dirname() does...
664 $catpaths[] = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
667 } else {
668 return array(); // no courses!
671 $CFG->coursemanager = trim($CFG->coursemanager);
672 if (empty($CFG->coursemanager)) {
673 return $courses;
676 $managerroles = split(',', $CFG->coursemanager);
677 $catctxids = '';
678 if (count($managerroles)) {
679 if ($allcats === true) {
680 $catpaths = array_unique($catpaths);
681 $ctxids = array();
682 foreach ($catpaths as $cpath) {
683 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
685 $ctxids = array_unique($ctxids);
686 $catctxids = implode( ',' , $ctxids);
687 unset($catpaths);
688 unset($cpath);
689 } else {
690 // take the ctx path from the first course
691 // as all categories will be the same...
692 $catpath = substr($catpath,1);
693 $catpath = preg_replace(':/\d+$:','',$catpath);
694 $catctxids = str_replace('/',',',$catpath);
696 if ($categoryclause !== '') {
697 $categoryclause = "AND $categoryclause";
700 * Note: Here we use a LEFT OUTER JOIN that can
701 * "optionally" match to avoid passing a ton of context
702 * ids in an IN() clause. Perhaps a subselect is faster.
704 * In any case, this SQL is not-so-nice over large sets of
705 * courses with no $categoryclause.
708 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
709 ra.hidden,
710 r.id AS roleid, r.name as rolename,
711 u.id AS userid, u.firstname, u.lastname
712 FROM {$CFG->prefix}role_assignments ra
713 JOIN {$CFG->prefix}context ctx
714 ON ra.contextid = ctx.id
715 JOIN {$CFG->prefix}user u
716 ON ra.userid = u.id
717 JOIN {$CFG->prefix}role r
718 ON ra.roleid = r.id
719 LEFT OUTER JOIN {$CFG->prefix}course c
720 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
721 WHERE ( c.id IS NOT NULL";
722 // under certain conditions, $catctxids is NULL
723 if($catctxids == NULL){
724 $sql .= ") ";
725 }else{
726 $sql .= " OR ra.contextid IN ($catctxids) )";
729 $sql .= "AND ra.roleid IN ({$CFG->coursemanager})
730 $categoryclause
731 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
732 $rs = get_recordset_sql($sql);
734 // This loop is fairly stupid as it stands - might get better
735 // results doing an initial pass clustering RAs by path.
736 while ($ra = rs_fetch_next_record($rs)) {
737 $user = new StdClass;
738 $user->id = $ra->userid; unset($ra->userid);
739 $user->firstname = $ra->firstname; unset($ra->firstname);
740 $user->lastname = $ra->lastname; unset($ra->lastname);
741 $ra->user = $user;
742 if ($ra->contextlevel == CONTEXT_SYSTEM) {
743 foreach ($courses as $k => $course) {
744 $courses[$k]->managers[] = $ra;
746 } elseif ($ra->contextlevel == CONTEXT_COURSECAT) {
747 if ($allcats === false) {
748 // It always applies
749 foreach ($courses as $k => $course) {
750 $courses[$k]->managers[] = $ra;
752 } else {
753 foreach ($courses as $k => $course) {
754 // Note that strpos() returns 0 as "matched at pos 0"
755 if (strpos($course->context->path, $ra->path.'/')===0) {
756 // Only add it to subpaths
757 $courses[$k]->managers[] = $ra;
761 } else { // course-level
762 if(!array_key_exists($ra->instanceid, $courses)) {
763 //this course is not in a list, probably a frontpage course
764 continue;
766 $courses[$ra->instanceid]->managers[] = $ra;
769 rs_close($rs);
772 return $courses;
776 * Convenience function - lists courses that a user has access to view.
778 * For admins and others with access to "every" course in the system, we should
779 * try to get courses with explicit RAs.
781 * NOTE: this function is heavily geared towards the perspective of the user
782 * passed in $userid. So it will hide courses that the user cannot see
783 * (for any reason) even if called from cron or from another $USER's
784 * perspective.
786 * If you really want to know what courses are assigned to the user,
787 * without any hiding or scheming, call the lower-level
788 * get_user_courses_bycap().
791 * Notes inherited from get_user_courses_bycap():
793 * - $fields is an array of fieldnames to ADD
794 * so name the fields you really need, which will
795 * be added and uniq'd
797 * - the course records have $c->context which is a fully
798 * valid context object. Saves you a query per course!
800 * @uses $CFG,$USER
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 {@link $COURSE} of course objects
808 function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
810 global $CFG,$USER;
812 // Guest's do not have any courses
813 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
814 if (has_capability('moodle/legacy:guest',$sitecontext,$userid,false)) {
815 return(array());
818 $basefields = array('id', 'category', 'sortorder',
819 'shortname', 'fullname', 'idnumber',
820 'teacher', 'teachers', 'student', 'students',
821 'guest', 'startdate', 'visible',
822 'newsitems', 'cost', 'enrol',
823 'groupmode', 'groupmodeforce');
825 if (!is_null($fields) && is_string($fields)) {
826 if (empty($fields)) {
827 $fields = $basefields;
828 } else {
829 // turn the fields from a string to an array that
830 // get_user_courses_bycap() will like...
831 $fields = explode(',',$fields);
832 $fields = array_map('trim', $fields);
833 $fields = array_unique(array_merge($basefields, $fields));
835 } elseif (is_array($fields)) {
836 $fields = array_unique(array_merge($basefields, $fields));
837 } else {
838 $fields = $basefields;
841 $orderby = '';
842 $sort = trim($sort);
843 if (!empty($sort)) {
844 $rawsorts = explode(',', $sort);
845 $sorts = array();
846 foreach ($rawsorts as $rawsort) {
847 $rawsort = trim($rawsort);
848 if (strpos($rawsort, 'c.') === 0) {
849 $rawsort = substr($rawsort, 2);
851 $sorts[] = trim($rawsort);
853 $sort = 'c.'.implode(',c.', $sorts);
854 $orderby = "ORDER BY $sort";
858 // Logged-in user - Check cached courses
860 // NOTE! it's a _string_ because
861 // - it's all we'll ever use
862 // - it serialises much more compact than an array
863 // this a big concern here - cost of serialise
864 // and unserialise gets huge as the session grows
866 // If the courses are too many - it won't be set
867 // for large numbers of courses, caching in the session
868 // has marginal benefits (costs too much, not
869 // worthwhile...) and we may hit SQL parser limits
870 // because we use IN()
872 if ($userid === $USER->id) {
873 if (isset($USER->loginascontext)
874 && $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
875 // list _only_ this course
876 // anything else is asking for trouble...
877 $courseids = $USER->loginascontext->instanceid;
878 } elseif (isset($USER->mycourses)
879 && is_string($USER->mycourses)) {
880 if ($USER->mycourses === '') {
881 // empty str means: user has no courses
882 // ... so do the easy thing...
883 return array();
884 } else {
885 $courseids = $USER->mycourses;
888 if (isset($courseids)) {
889 // The data massaging here MUST be kept in sync with
890 // get_user_courses_bycap() so we return
891 // the same...
892 // (but here we don't need to check has_cap)
893 $coursefields = 'c.' .join(',c.', $fields);
894 $sql = "SELECT $coursefields,
895 ctx.id AS ctxid, ctx.path AS ctxpath,
896 ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel,
897 cc.path AS categorypath
898 FROM {$CFG->prefix}course c
899 JOIN {$CFG->prefix}course_categories cc
900 ON c.category=cc.id
901 JOIN {$CFG->prefix}context ctx
902 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
903 WHERE c.id IN ($courseids)
904 $orderby";
905 $rs = get_recordset_sql($sql);
906 $courses = array();
907 $cc = 0; // keep count
908 while ($c = rs_fetch_next_record($rs)) {
909 // build the context obj
910 $c = make_context_subobj($c);
912 if ($limit > 0 && $cc >= $limit) {
913 break;
916 $courses[$c->id] = $c;
917 $cc++;
919 rs_close($rs);
920 return $courses;
924 // Non-cached - get accessinfo
925 if ($userid === $USER->id && isset($USER->access)) {
926 $accessinfo = $USER->access;
927 } else {
928 $accessinfo = get_user_access_sitewide($userid);
932 $courses = get_user_courses_bycap($userid, 'moodle/course:view', $accessinfo,
933 $doanything, $sort, $fields,
934 $limit);
936 $cats = NULL;
937 // If we have to walk category visibility
938 // to eval course visibility, get the categories
939 if (empty($CFG->allowvisiblecoursesinhiddencategories)) {
940 $sql = "SELECT cc.id, cc.path, cc.visible,
941 ctx.id AS ctxid, ctx.path AS ctxpath,
942 ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel
943 FROM {$CFG->prefix}course_categories cc
944 JOIN {$CFG->prefix}context ctx ON (cc.id = ctx.instanceid)
945 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT."
946 ORDER BY cc.id";
947 $rs = get_recordset_sql($sql);
949 // Using a temporary array instead of $cats here, to avoid a "true" result when isnull($cats) further down
950 $categories = array();
951 while ($course_cat = rs_fetch_next_record($rs)) {
952 // build the context obj
953 $course_cat = make_context_subobj($course_cat);
954 $categories[$course_cat->id] = $course_cat;
956 rs_close($rs);
958 if (!empty($categories)) {
959 $cats = $categories;
962 unset($course_cat);
965 // Strangely, get_my_courses() is expected to return the
966 // array keyed on id, which messes up the sorting
967 // So do that, and also cache the ids in the session if appropriate
969 $kcourses = array();
970 $courses_count = count($courses);
971 $cacheids = NULL;
972 $vcatpaths = array();
973 if ($userid === $USER->id && $courses_count < 500) {
974 $cacheids = array();
976 for ($n=0; $n<$courses_count; $n++) {
979 // Check whether $USER (not $userid) can _actually_ see them
980 // Easy if $CFG->allowvisiblecoursesinhiddencategories
981 // is set, and we don't have to care about categories.
982 // Lots of work otherwise... (all in mem though!)
984 $cansee = false;
985 if (is_null($cats)) { // easy rules!
986 if ($courses[$n]->visible == true) {
987 $cansee = true;
988 } elseif (has_capability('moodle/course:viewhiddencourses',
989 $courses[$n]->context, $USER->id)) {
990 $cansee = true;
992 } else {
994 // Is the cat visible?
995 // we have to assume it _is_ visible
996 // so we can shortcut when we find a hidden one
998 $viscat = true;
999 $cpath = $courses[$n]->categorypath;
1000 if (isset($vcatpaths[$cpath])) {
1001 $viscat = $vcatpaths[$cpath];
1002 } else {
1003 $cpath = substr($cpath,1); // kill leading slash
1004 $cpath = explode('/',$cpath);
1005 $ccct = count($cpath);
1006 for ($m=0;$m<$ccct;$m++) {
1007 $ccid = $cpath[$m];
1008 if ($cats[$ccid]->visible==false) {
1009 $viscat = false;
1010 break;
1013 $vcatpaths[$courses[$n]->categorypath] = $viscat;
1017 // Perhaps it's actually visible to $USER
1018 // check moodle/category:viewhiddencategories
1020 // The name isn't obvious, but the description says
1021 // "See hidden categories" so the user shall see...
1022 // But also check if the allowvisiblecoursesinhiddencategories setting is true, and check for course visibility
1023 if ($viscat === false) {
1024 $catctx = $cats[$courses[$n]->category]->context;
1025 if (has_capability('moodle/category:viewhiddencategories', $catctx, $USER->id)) {
1026 $vcatpaths[$courses[$n]->categorypath] = true;
1027 $viscat = true;
1028 } elseif ($CFG->allowvisiblecoursesinhiddencategories && $courses[$n]->visible == true) {
1029 $viscat = true;
1034 // Decision matrix
1036 if ($viscat === true) {
1037 if ($courses[$n]->visible == true) {
1038 $cansee = true;
1039 } elseif (has_capability('moodle/course:viewhiddencourses',
1040 $courses[$n]->context, $USER->id)) {
1041 $cansee = true;
1045 if ($cansee === true) {
1046 $kcourses[$courses[$n]->id] = $courses[$n];
1047 if (is_array($cacheids)) {
1048 $cacheids[] = $courses[$n]->id;
1052 if (is_array($cacheids)) {
1053 // Only happens
1054 // - for the logged in user
1055 // - below the threshold (500)
1056 // empty string is _valid_
1057 $USER->mycourses = join(',',$cacheids);
1058 } elseif ($userid === $USER->id && isset($USER->mycourses)) {
1059 // cheap sanity check
1060 unset($USER->mycourses);
1063 return $kcourses;
1067 * A list of courses that match a search
1069 * @uses $CFG
1070 * @param array $searchterms ?
1071 * @param string $sort ?
1072 * @param int $page ?
1073 * @param int $recordsperpage ?
1074 * @param int $totalcount Passed in by reference. ?
1075 * @return object {@link $COURSE} records
1077 function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
1079 global $CFG;
1081 //to allow case-insensitive search for postgesql
1082 if ($CFG->dbfamily == 'postgres') {
1083 $LIKE = 'ILIKE';
1084 $NOTLIKE = 'NOT ILIKE'; // case-insensitive
1085 $REGEXP = '~*';
1086 $NOTREGEXP = '!~*';
1087 } else {
1088 $LIKE = 'LIKE';
1089 $NOTLIKE = 'NOT LIKE';
1090 $REGEXP = 'REGEXP';
1091 $NOTREGEXP = 'NOT REGEXP';
1094 $fullnamesearch = '';
1095 $summarysearch = '';
1096 $idnumbersearch = '';
1097 $shortnamesearch = '';
1099 foreach ($searchterms as $searchterm) {
1101 $NOT = ''; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1102 /// will use it to simulate the "-" operator with LIKE clause
1104 /// Under Oracle and MSSQL, trim the + and - operators and perform
1105 /// simpler LIKE (or NOT LIKE) queries
1106 if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
1107 if (substr($searchterm, 0, 1) == '-') {
1108 $NOT = ' NOT ';
1110 $searchterm = trim($searchterm, '+-');
1113 if ($fullnamesearch) {
1114 $fullnamesearch .= ' AND ';
1116 if ($summarysearch) {
1117 $summarysearch .= ' AND ';
1119 if ($idnumbersearch) {
1120 $idnumbersearch .= ' AND ';
1122 if ($shortnamesearch) {
1123 $shortnamesearch .= ' AND ';
1126 if (substr($searchterm,0,1) == '+') {
1127 $searchterm = substr($searchterm,1);
1128 $summarysearch .= " c.summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1129 $fullnamesearch .= " c.fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1130 $idnumbersearch .= " c.idnumber $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1131 $shortnamesearch .= " c.shortname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1132 } else if (substr($searchterm,0,1) == "-") {
1133 $searchterm = substr($searchterm,1);
1134 $summarysearch .= " c.summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1135 $fullnamesearch .= " c.fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1136 $idnumbersearch .= " c.idnumber $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1137 $shortnamesearch .= " c.shortname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1138 } else {
1139 $summarysearch .= ' summary '. $NOT . $LIKE .' \'%'. $searchterm .'%\' ';
1140 $fullnamesearch .= ' fullname '. $NOT . $LIKE .' \'%'. $searchterm .'%\' ';
1141 $idnumbersearch .= ' idnumber '. $NOT . $LIKE .' \'%'. $searchterm .'%\' ';
1142 $shortnamesearch .= ' shortname '. $NOT . $LIKE .' \'%'. $searchterm .'%\' ';
1147 $sql = "SELECT c.*,
1148 ctx.id AS ctxid, ctx.path AS ctxpath,
1149 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1150 FROM {$CFG->prefix}course c
1151 JOIN {$CFG->prefix}context ctx
1152 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
1153 WHERE (( $fullnamesearch ) OR ( $summarysearch ) OR ( $idnumbersearch ) OR ( $shortnamesearch ))
1154 AND category > 0
1155 ORDER BY " . $sort;
1157 $courses = array();
1159 if ($rs = get_recordset_sql($sql)) {
1162 // Tiki pagination
1163 $limitfrom = $page * $recordsperpage;
1164 $limitto = $limitfrom + $recordsperpage;
1165 $c = 0; // counts how many visible courses we've seen
1167 while ($course = rs_fetch_next_record($rs)) {
1168 $course = make_context_subobj($course);
1169 if ($course->visible || has_capability('moodle/course:viewhiddencourses', $course->context)) {
1170 // Don't exit this loop till the end
1171 // we need to count all the visible courses
1172 // to update $totalcount
1173 if ($c >= $limitfrom && $c < $limitto) {
1174 $courses[] = $course;
1176 $c++;
1181 // our caller expects 2 bits of data - our return
1182 // array, and an updated $totalcount
1183 $totalcount = $c;
1184 return $courses;
1189 * Returns a sorted list of categories. Each category object has a context
1190 * property that is a context object.
1192 * When asking for $parent='none' it will return all the categories, regardless
1193 * of depth. Wheen asking for a specific parent, the default is to return
1194 * a "shallow" resultset. Pass false to $shallow and it will return all
1195 * the child categories as well.
1198 * @param string $parent The parent category if any
1199 * @param string $sort the sortorder
1200 * @param bool $shallow - set to false to get the children too
1201 * @return array of categories
1203 function get_categories($parent='none', $sort=NULL, $shallow=true) {
1204 global $CFG;
1206 if ($sort === NULL) {
1207 $sort = 'ORDER BY cc.sortorder ASC';
1208 } elseif ($sort ==='') {
1209 // leave it as empty
1210 } else {
1211 $sort = "ORDER BY $sort";
1214 if ($parent === 'none') {
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 $sort";
1222 } elseif ($shallow) {
1223 $parent = (int)$parent;
1224 $sql = "SELECT cc.*,
1225 ctx.id AS ctxid, ctx.path AS ctxpath,
1226 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1227 FROM {$CFG->prefix}course_categories cc
1228 JOIN {$CFG->prefix}context ctx
1229 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
1230 WHERE cc.parent=$parent
1231 $sort";
1232 } else {
1233 $parent = (int)$parent;
1234 $sql = "SELECT cc.*,
1235 ctx.id AS ctxid, ctx.path AS ctxpath,
1236 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1237 FROM {$CFG->prefix}course_categories cc
1238 JOIN {$CFG->prefix}context ctx
1239 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
1240 JOIN {$CFG->prefix}course_categories ccp
1241 ON ((cc.parent=ccp.id) OR (cc.path LIKE ".sql_concat('ccp.path',"'/%'")."))
1242 WHERE ccp.id=$parent
1243 $sort";
1245 $categories = array();
1247 if( $rs = get_recordset_sql($sql) ){
1248 while ($cat = rs_fetch_next_record($rs)) {
1249 $cat = make_context_subobj($cat);
1250 if ($cat->visible || has_capability('moodle/category:viewhiddencategories',$cat->context)) {
1251 $categories[$cat->id] = $cat;
1255 return $categories;
1260 * Returns an array of category ids of all the subcategories for a given
1261 * category.
1262 * @param $catid - The id of the category whose subcategories we want to find.
1263 * @return array of category ids.
1265 function get_all_subcategories($catid) {
1267 $subcats = array();
1269 if ($categories = get_records('course_categories', 'parent', $catid)) {
1270 foreach ($categories as $cat) {
1271 array_push($subcats, $cat->id);
1272 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
1275 return $subcats;
1280 * This recursive function makes sure that the courseorder is consecutive
1282 * @param type description
1284 * $n is the starting point, offered only for compatilibity -- will be ignored!
1285 * $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
1286 * safely from 1.4 to 1.5
1288 function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
1290 global $CFG;
1292 $count = 0;
1294 $catgap = 1000; // "standard" category gap
1295 $tolerance = 200; // how "close" categories can get
1297 if ($categoryid > 0){
1298 // update depth and path
1299 $cat = get_record('course_categories', 'id', $categoryid);
1300 if ($cat->parent == 0) {
1301 $depth = 0;
1302 $path = '';
1303 } else if ($depth == 0 ) { // doesn't make sense; get from DB
1304 // this is only called if the $depth parameter looks dodgy
1305 $parent = get_record('course_categories', 'id', $cat->parent);
1306 $path = $parent->path;
1307 $depth = $parent->depth;
1309 $path = $path . '/' . $categoryid;
1310 $depth = $depth + 1;
1312 if ($cat->path !== $path) {
1313 set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
1315 if ($cat->depth != $depth) {
1316 set_field('course_categories', 'depth', $depth, 'id', $categoryid);
1320 // get some basic info about courses in the category
1321 $info = get_record_sql('SELECT MIN(sortorder) AS min,
1322 MAX(sortorder) AS max,
1323 COUNT(sortorder) AS count
1324 FROM ' . $CFG->prefix . 'course
1325 WHERE category=' . $categoryid);
1326 if (is_object($info)) { // no courses?
1327 $max = $info->max;
1328 $count = $info->count;
1329 $min = $info->min;
1330 unset($info);
1333 if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
1334 $n = $min;
1337 // $hasgap flag indicates whether there's a gap in the sequence
1338 $hasgap = false;
1339 if ($max-$min+1 != $count) {
1340 $hasgap = true;
1343 // $mustshift indicates whether the sequence must be shifted to
1344 // meet its range
1345 $mustshift = false;
1346 if ($min < $n-$tolerance || $min > $n+$tolerance+$catgap ) {
1347 $mustshift = true;
1350 // actually sort only if there are courses,
1351 // and we meet one ofthe triggers:
1352 // - safe flag
1353 // - they are not in a continuos block
1354 // - they are too close to the 'bottom'
1355 if ($count && ( $safe || $hasgap || $mustshift ) ) {
1356 // special, optimized case where all we need is to shift
1357 if ( $mustshift && !$safe && !$hasgap) {
1358 $shift = $n + $catgap - $min;
1359 if ($shift < $count) {
1360 $shift = $count + $catgap;
1362 // UPDATE course SET sortorder=sortorder+$shift
1363 execute_sql("UPDATE {$CFG->prefix}course
1364 SET sortorder=sortorder+$shift
1365 WHERE category=$categoryid", 0);
1366 $n = $n + $catgap + $count;
1368 } else { // do it slowly
1369 $n = $n + $catgap;
1370 // if the new sequence overlaps the current sequence, lack of transactions
1371 // will stop us -- shift things aside for a moment...
1372 if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbfamily==='mysql')) {
1373 $shift = $max + $n + 1000;
1374 execute_sql("UPDATE {$CFG->prefix}course
1375 SET sortorder=sortorder+$shift
1376 WHERE category=$categoryid", 0);
1379 $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
1380 begin_sql();
1381 $tx = true; // transaction sanity
1382 foreach ($courses as $course) {
1383 if ($tx && $course->sortorder != $n ) { // save db traffic
1384 $tx = $tx && set_field('course', 'sortorder', $n,
1385 'id', $course->id);
1387 $n++;
1389 if ($tx) {
1390 commit_sql();
1391 } else {
1392 rollback_sql();
1393 if (!$safe) {
1394 // if we failed when called with !safe, try
1395 // to recover calling self with safe=true
1396 return fix_course_sortorder($categoryid, $n, true, $depth, $path);
1401 set_field('course_categories', 'coursecount', $count, 'id', $categoryid);
1403 // $n could need updating
1404 $max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid");
1405 if ($max > $n) {
1406 $n = $max;
1409 if ($categories = get_categories($categoryid)) {
1410 foreach ($categories as $category) {
1411 $n = fix_course_sortorder($category->id, $n, $safe, $depth, $path);
1415 return $n+1;
1419 * Ensure all courses have a valid course category
1420 * useful if a category has been removed manually
1422 function fix_coursecategory_orphans() {
1424 global $CFG;
1426 // Note: the handling of sortorder here is arguably
1427 // open to race conditions. Hard to fix here, unlikely
1428 // to hit anyone in production.
1430 $sql = "SELECT c.id, c.category, c.shortname
1431 FROM {$CFG->prefix}course c
1432 LEFT OUTER JOIN {$CFG->prefix}course_categories cc ON c.category=cc.id
1433 WHERE cc.id IS NULL AND c.id != " . SITEID;
1435 $rs = get_recordset_sql($sql);
1437 if (!rs_EOF($rs)) { // we have some orphans
1439 // the "default" category is the lowest numbered...
1440 $default = get_field_sql("SELECT MIN(id)
1441 FROM {$CFG->prefix}course_categories");
1442 $sortorder = get_field_sql("SELECT MAX(sortorder)
1443 FROM {$CFG->prefix}course
1444 WHERE category=$default");
1447 begin_sql();
1448 $tx = true;
1449 while ($tx && $course = rs_fetch_next_record($rs)) {
1450 $tx = $tx && set_field('course', 'category', $default, 'id', $course->id);
1451 $tx = $tx && set_field('course', 'sortorder', ++$sortorder, 'id', $course->id);
1453 if ($tx) {
1454 commit_sql();
1455 } else {
1456 rollback_sql();
1459 rs_close($rs);
1463 * List of remote courses that a user has access to via MNET.
1464 * Works only on the IDP
1466 * @uses $CFG, $USER
1467 * @return array {@link $COURSE} of course objects
1469 function get_my_remotecourses($userid=0) {
1470 global $CFG, $USER;
1472 if (empty($userid)) {
1473 $userid = $USER->id;
1476 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1477 c.hostid, c.summary, c.cat_name,
1478 h.name AS hostname
1479 FROM {$CFG->prefix}mnet_enrol_course c
1480 JOIN {$CFG->prefix}mnet_enrol_assignments a ON c.id=a.courseid
1481 JOIN {$CFG->prefix}mnet_host h ON c.hostid=h.id
1482 WHERE a.userid={$userid}";
1484 return get_records_sql($sql);
1488 * List of remote hosts that a user has access to via MNET.
1489 * Works on the SP
1491 * @uses $CFG, $USER
1492 * @return array of host objects
1494 function get_my_remotehosts() {
1495 global $CFG, $USER;
1497 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1498 return false; // Return nothing on the IDP
1500 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1501 return $USER->mnet_foreign_host_array;
1503 return false;
1507 * This function creates a default separated/connected scale
1509 * This function creates a default separated/connected scale
1510 * so there's something in the database. The locations of
1511 * strings and files is a bit odd, but this is because we
1512 * need to maintain backward compatibility with many different
1513 * existing language translations and older sites.
1515 * @uses $CFG
1517 function make_default_scale() {
1519 global $CFG;
1521 $defaultscale = NULL;
1522 $defaultscale->courseid = 0;
1523 $defaultscale->userid = 0;
1524 $defaultscale->name = get_string('separateandconnected');
1525 $defaultscale->scale = get_string('postrating1', 'forum').','.
1526 get_string('postrating2', 'forum').','.
1527 get_string('postrating3', 'forum');
1528 $defaultscale->timemodified = time();
1530 /// Read in the big description from the file. Note this is not
1531 /// HTML (despite the file extension) but Moodle format text.
1532 $parentlang = get_string('parentlanguage');
1533 if ($parentlang[0] == '[') {
1534 $parentlang = '';
1536 if (is_readable($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1537 $file = file($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1538 } else if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1539 $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1540 } else if ($parentlang and is_readable($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1541 $file = file($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
1542 } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1543 $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
1544 } else if (is_readable($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html')) {
1545 $file = file($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html');
1546 } else {
1547 $file = '';
1550 $defaultscale->description = addslashes(implode('', $file));
1552 if ($defaultscale->id = insert_record('scale', $defaultscale)) {
1553 execute_sql('UPDATE '. $CFG->prefix .'forum SET scale = \''. $defaultscale->id .'\'', false);
1559 * Returns a menu of all available scales from the site as well as the given course
1561 * @uses $CFG
1562 * @param int $courseid The id of the course as found in the 'course' table.
1563 * @return object
1565 function get_scales_menu($courseid=0) {
1567 global $CFG;
1569 $sql = "SELECT id, name FROM {$CFG->prefix}scale
1570 WHERE courseid = '0' or courseid = '$courseid'
1571 ORDER BY courseid ASC, name ASC";
1573 if ($scales = get_records_sql_menu($sql)) {
1574 return $scales;
1577 make_default_scale();
1579 return get_records_sql_menu($sql);
1585 * Given a set of timezone records, put them in the database, replacing what is there
1587 * @uses $CFG
1588 * @param array $timezones An array of timezone records
1590 function update_timezone_records($timezones) {
1591 /// Given a set of timezone records, put them in the database
1593 global $CFG;
1595 /// Clear out all the old stuff
1596 execute_sql('TRUNCATE TABLE '.$CFG->prefix.'timezone', false);
1598 /// Insert all the new stuff
1599 foreach ($timezones as $timezone) {
1600 if (is_array($timezone)) {
1601 $timezone = (object)$timezone;
1603 insert_record('timezone', $timezone);
1608 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1611 * Just gets a raw list of all modules in a course
1613 * @uses $CFG
1614 * @param int $courseid The id of the course as found in the 'course' table.
1615 * @return object
1617 function get_course_mods($courseid) {
1618 global $CFG;
1620 if (empty($courseid)) {
1621 return false; // avoid warnings
1624 return get_records_sql("SELECT cm.*, m.name as modname
1625 FROM {$CFG->prefix}modules m,
1626 {$CFG->prefix}course_modules cm
1627 WHERE cm.course = ".intval($courseid)."
1628 AND cm.module = m.id AND m.visible = 1"); // no disabled mods
1633 * Given an id of a course module, finds the coursemodule description
1635 * @param string $modulename name of module type, eg. resource, assignment,...
1636 * @param int $cmid course module id (id in course_modules table)
1637 * @param int $courseid optional course id for extra validation
1638 * @return object course module instance with instance and module name
1640 function get_coursemodule_from_id($modulename, $cmid, $courseid=0) {
1642 global $CFG;
1644 $courseselect = ($courseid) ? 'cm.course = '.intval($courseid).' AND ' : '';
1646 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1647 FROM {$CFG->prefix}course_modules cm,
1648 {$CFG->prefix}modules md,
1649 {$CFG->prefix}$modulename m
1650 WHERE $courseselect
1651 cm.id = ".intval($cmid)." AND
1652 cm.instance = m.id AND
1653 md.name = '$modulename' AND
1654 md.id = cm.module");
1658 * Given an instance number of a module, finds the coursemodule description
1660 * @param string $modulename name of module type, eg. resource, assignment,...
1661 * @param int $instance module instance number (id in resource, assignment etc. table)
1662 * @param int $courseid optional course id for extra validation
1663 * @return object course module instance with instance and module name
1665 function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
1667 global $CFG;
1669 $courseselect = ($courseid) ? 'cm.course = '.intval($courseid).' AND ' : '';
1671 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1672 FROM {$CFG->prefix}course_modules cm,
1673 {$CFG->prefix}modules md,
1674 {$CFG->prefix}$modulename m
1675 WHERE $courseselect
1676 cm.instance = m.id AND
1677 md.name = '$modulename' AND
1678 md.id = cm.module AND
1679 m.id = ".intval($instance));
1684 * Returns all course modules of given activity in course
1685 * @param string $modulename (forum, quiz, etc.)
1686 * @param int $courseid
1687 * @param string $extrafields extra fields starting with m.
1688 * @return array of cm objects, false if not found or error
1690 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1691 global $CFG;
1693 if (!empty($extrafields)) {
1694 $extrafields = ", $extrafields";
1696 return get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1697 FROM {$CFG->prefix}course_modules cm,
1698 {$CFG->prefix}modules md,
1699 {$CFG->prefix}$modulename m
1700 WHERE cm.course = $courseid AND
1701 cm.instance = m.id AND
1702 md.name = '$modulename' AND
1703 md.id = cm.module");
1707 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1709 * Returns an array of all the active instances of a particular
1710 * module in given courses, sorted in the order they are defined
1711 * in the course. Returns an empty array on any errors.
1713 * The returned objects includle the columns cw.section, cm.visible,
1714 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1716 * @param string $modulename The name of the module to get instances for
1717 * @param array $courses an array of course objects.
1718 * @return array of module instance objects, including some extra fields from the course_modules
1719 * and course_sections tables, or an empty array if an error occurred.
1721 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1722 global $CFG;
1724 $outputarray = array();
1726 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1727 return $outputarray;
1730 if (!$rawmods = get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1731 cm.groupmode, cm.groupingid, cm.groupmembersonly
1732 FROM {$CFG->prefix}course_modules cm,
1733 {$CFG->prefix}course_sections cw,
1734 {$CFG->prefix}modules md,
1735 {$CFG->prefix}$modulename m
1736 WHERE cm.course IN (".implode(',',array_keys($courses)).") AND
1737 cm.instance = m.id AND
1738 cm.section = cw.id AND
1739 md.name = '$modulename' AND
1740 md.id = cm.module")) {
1741 return $outputarray;
1744 require_once($CFG->dirroot.'/course/lib.php');
1746 foreach ($courses as $course) {
1747 $modinfo = get_fast_modinfo($course, $userid);
1749 if (empty($modinfo->instances[$modulename])) {
1750 continue;
1753 foreach ($modinfo->instances[$modulename] as $cm) {
1754 if (!$includeinvisible and !$cm->uservisible) {
1755 continue;
1757 if (!isset($rawmods[$cm->id])) {
1758 continue;
1760 $instance = $rawmods[$cm->id];
1761 if (!empty($cm->extra)) {
1762 $instance->extra = urlencode($cm->extra); // bc compatibility
1764 $outputarray[] = $instance;
1768 return $outputarray;
1772 * Returns an array of all the active instances of a particular module in a given course,
1773 * sorted in the order they are defined.
1775 * Returns an array of all the active instances of a particular
1776 * module in a given course, sorted in the order they are defined
1777 * in the course. Returns an empty array on any errors.
1779 * The returned objects includle the columns cw.section, cm.visible,
1780 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1782 * @param string $modulename The name of the module to get instances for
1783 * @param object $course The course obect.
1784 * @return array of module instance objects, including some extra fields from the course_modules
1785 * and course_sections tables, or an empty array if an error occurred.
1787 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1788 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1793 * Determine whether a module instance is visible within a course
1795 * Given a valid module object with info about the id and course,
1796 * and the module's type (eg "forum") returns whether the object
1797 * is visible or not, groupmembersonly visibility not tested
1799 * @uses $CFG
1800 * @param $moduletype Name of the module eg 'forum'
1801 * @param $module Object which is the instance of the module
1802 * @return bool
1804 function instance_is_visible($moduletype, $module) {
1806 global $CFG;
1808 if (!empty($module->id)) {
1809 if ($records = get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1810 FROM {$CFG->prefix}course_modules cm,
1811 {$CFG->prefix}modules m
1812 WHERE cm.course = '$module->course' AND
1813 cm.module = m.id AND
1814 m.name = '$moduletype' AND
1815 cm.instance = '$module->id'")) {
1817 foreach ($records as $record) { // there should only be one - use the first one
1818 return $record->visible;
1822 return true; // visible by default!
1826 * Determine whether a course module is visible within a course,
1827 * this is different from instance_is_visible() - faster and visibility for user
1829 * @param object $cm object
1830 * @param int $userid empty means current user
1831 * @return bool
1833 function coursemodule_visible_for_user($cm, $userid=0) {
1834 global $USER;
1836 if (empty($cm->id)) {
1837 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1838 return false;
1840 if (empty($userid)) {
1841 $userid = $USER->id;
1843 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1844 return false;
1846 return groups_course_module_visible($cm, $userid);
1852 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1856 * Add an entry to the log table.
1858 * Add an entry to the log table. These are "action" focussed rather
1859 * than web server hits, and provide a way to easily reconstruct what
1860 * any particular student has been doing.
1862 * @uses $CFG
1863 * @uses $USER
1864 * @uses $db
1865 * @uses $REMOTE_ADDR
1866 * @uses SITEID
1867 * @param int $courseid The course id
1868 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
1869 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1870 * @param string $url The file and parameters used to see the results of the action
1871 * @param string $info Additional description information
1872 * @param string $cm The course_module->id if there is one
1873 * @param string $user If log regards $user other than $USER
1875 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1876 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1877 // This is for a good reason: it is the most frequently used DB update function,
1878 // so it has been optimised for speed.
1879 global $db, $CFG, $USER;
1881 // sanitize all incoming data
1882 $courseid = clean_param($courseid, PARAM_INT);
1883 $module = clean_param($module, PARAM_SAFEDIR);
1884 $action = addslashes($action);
1885 // url cleaned bellow
1886 // info cleaned bellow
1887 $cm = clean_param($cm, PARAM_INT);
1888 $user = clean_param($user, PARAM_INT);
1890 if ($user) {
1891 $userid = $user;
1892 } else {
1893 if (!empty($USER->realuser)) { // Don't log
1894 return;
1896 $userid = empty($USER->id) ? '0' : $USER->id;
1899 $REMOTE_ADDR = getremoteaddr();
1900 if (empty($REMOTE_ADDR)) {
1901 $REMOTE_ADDR = '0.0.0.0';
1904 $timenow = time();
1905 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1906 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
1909 // Restrict length of log lines to the space actually available in the
1910 // database so that it doesn't cause a DB error. Log a warning so that
1911 // developers can avoid doing things which are likely to cause this on a
1912 // routine basis.
1913 $tl=textlib_get_instance();
1914 if(!empty($info) && $tl->strlen($info)>255) {
1915 $info=$tl->substr($info,0,252).'...';
1916 debugging('Warning: logged very long info',DEBUG_DEVELOPER);
1918 $info = addslashes($info);
1919 // Note: Unlike $info, URL appears to be already slashed before this function
1920 // is called. Since database limits are for the data before slashes, we need
1921 // to remove them...
1922 $url=stripslashes($url);
1923 // If the 100 field size is changed, also need to alter print_log in course/lib.php
1924 if(!empty($url) && $tl->strlen($url)>100) {
1925 $url=$tl->substr($url,0,97).'...';
1926 debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
1928 $url=addslashes($url);
1930 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; $PERF->logwrites++;};
1932 $info = empty($info) ? sql_empty() : $info; // Use proper empties for each database
1933 $url = empty($url) ? sql_empty() : $url;
1934 $sql ='INSERT INTO '. $CFG->prefix .'log (time, userid, course, ip, module, cmid, action, url, info)
1935 VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')";
1937 $result = $db->Execute($sql);
1939 // MDL-11893, alert $CFG->supportemail if insert into log failed
1940 if (!$result && $CFG->supportemail) {
1941 $site = get_site();
1942 $subject = 'Insert into log failed at your moodle site '.$site->fullname;
1943 $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";
1944 $message .= "The failed SQL is:\n\n" . $sql;
1946 // email_to_user is not usable because email_to_user tries to write to the logs table,
1947 // and this will get caught in an infinite loop, if disk is full
1948 if (empty($CFG->noemailever)) {
1949 $lasttime = get_config('admin', 'lastloginserterrormail');
1950 if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
1951 mail($CFG->supportemail, $subject, $message);
1952 set_config('lastloginserterrormail', time(), 'admin');
1957 if (!$result) {
1958 debugging('Error: Could not insert a new entry to the Moodle log', DEBUG_ALL);
1964 * Store user last access times - called when use enters a course or site
1966 * Note: we use ADOdb code directly in this function to save some CPU
1967 * cycles here and there. They are simple operations not needing any
1968 * of the postprocessing performed by dmllib.php
1970 * @param int $courseid, empty means site
1971 * @return void
1973 function user_accesstime_log($courseid=0) {
1975 global $USER, $CFG, $PERF, $db;
1977 if (!isloggedin() or !empty($USER->realuser)) {
1978 // no access tracking
1979 return;
1982 if (empty($courseid)) {
1983 $courseid = SITEID;
1986 $timenow = time();
1988 /// Store site lastaccess time for the current user
1989 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1990 /// Update $USER->lastaccess for next checks
1991 $USER->lastaccess = $timenow;
1992 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
1994 $remoteaddr = getremoteaddr();
1995 if (empty($remoteaddr)) {
1996 $remoteaddr = '0.0.0.0';
1998 if ($db->Execute("UPDATE {$CFG->prefix}user
1999 SET lastip = '$remoteaddr', lastaccess = $timenow
2000 WHERE id = $USER->id")) {
2001 } else {
2002 debugging('Error: Could not update global user lastaccess information'); // Don't throw an error
2004 /// Remove this record from record cache since it will change
2005 if (!empty($CFG->rcache)) {
2006 rcache_unset('user', $USER->id);
2010 if ($courseid == SITEID) {
2011 /// no user_lastaccess for frontpage
2012 return;
2015 /// Store course lastaccess times for the current user
2016 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
2017 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
2019 $exists = false; // To detect if the user_lastaccess record exists or no
2020 if ($rs = $db->Execute("SELECT timeaccess
2021 FROM {$CFG->prefix}user_lastaccess
2022 WHERE userid = $USER->id AND courseid = $courseid")) {
2023 if (!$rs->EOF) {
2024 $exists = true;
2025 $lastaccess = reset($rs->fields);
2026 if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
2027 /// no need to update now, it was updated recently in concurrent login ;-)
2028 $rs->Close();
2029 return;
2032 $rs->Close();
2035 /// Update course lastaccess for next checks
2036 $USER->currentcourseaccess[$courseid] = $timenow;
2037 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; };
2039 if ($exists) { // user_lastaccess record exists, update it
2040 if ($db->Execute("UPDATE {$CFG->prefix}user_lastaccess
2041 SET timeaccess = $timenow
2042 WHERE userid = $USER->id AND courseid = $courseid")) {
2043 } else {
2044 debugging('Error: Could not update course user lastacess information'); // Don't throw an error
2047 } else { // user lastaccess record doesn't exist, insert it
2048 if ($db->Execute("INSERT INTO {$CFG->prefix}user_lastaccess
2049 (userid, courseid, timeaccess)
2050 VALUES ($USER->id, $courseid, $timenow)")) {
2051 } else {
2052 debugging('Error: Could not insert course user lastaccess information'); // Don't throw an error
2059 * Select all log records based on SQL criteria
2061 * @uses $CFG
2062 * @param string $select SQL select criteria
2063 * @param string $order SQL order by clause to sort the records returned
2064 * @param string $limitfrom ?
2065 * @param int $limitnum ?
2066 * @param int $totalcount Passed in by reference.
2067 * @return object
2068 * @todo Finish documenting this function
2070 function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
2071 global $CFG;
2073 if ($order) {
2074 $order = 'ORDER BY '. $order;
2077 $selectsql = $CFG->prefix .'log l LEFT JOIN '. $CFG->prefix .'user u ON l.userid = u.id '. ((strlen($select) > 0) ? 'WHERE '. $select : '');
2078 $countsql = $CFG->prefix.'log l '.((strlen($select) > 0) ? ' WHERE '. $select : '');
2080 $totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql");
2082 return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture
2083 FROM '. $selectsql .' '. $order, $limitfrom, $limitnum) ;
2088 * Select all log records for a given course and user
2090 * @uses $CFG
2091 * @uses DAYSECS
2092 * @param int $userid The id of the user as found in the 'user' table.
2093 * @param int $courseid The id of the course as found in the 'course' table.
2094 * @param string $coursestart ?
2095 * @todo Finish documenting this function
2097 function get_logs_usercourse($userid, $courseid, $coursestart) {
2098 global $CFG;
2100 if ($courseid) {
2101 $courseselect = ' AND course = \''. $courseid .'\' ';
2102 } else {
2103 $courseselect = '';
2106 return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS .") as day, count(*) as num
2107 FROM {$CFG->prefix}log
2108 WHERE userid = '$userid'
2109 AND time > '$coursestart' $courseselect
2110 GROUP BY floor((time - $coursestart)/". DAYSECS .") ");
2114 * Select all log records for a given course, user, and day
2116 * @uses $CFG
2117 * @uses HOURSECS
2118 * @param int $userid The id of the user as found in the 'user' table.
2119 * @param int $courseid The id of the course as found in the 'course' table.
2120 * @param string $daystart ?
2121 * @return object
2122 * @todo Finish documenting this function
2124 function get_logs_userday($userid, $courseid, $daystart) {
2125 global $CFG;
2127 if ($courseid) {
2128 $courseselect = ' AND course = \''. $courseid .'\' ';
2129 } else {
2130 $courseselect = '';
2133 return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS .") as hour, count(*) as num
2134 FROM {$CFG->prefix}log
2135 WHERE userid = '$userid'
2136 AND time > '$daystart' $courseselect
2137 GROUP BY floor((time - $daystart)/". HOURSECS .") ");
2141 * Returns an object with counts of failed login attempts
2143 * Returns information about failed login attempts. If the current user is
2144 * an admin, then two numbers are returned: the number of attempts and the
2145 * number of accounts. For non-admins, only the attempts on the given user
2146 * are shown.
2148 * @param string $mode Either 'admin', 'teacher' or 'everybody'
2149 * @param string $username The username we are searching for
2150 * @param string $lastlogin The date from which we are searching
2151 * @return int
2153 function count_login_failures($mode, $username, $lastlogin) {
2155 $select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin;
2157 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Return information about all accounts
2158 if ($count->attempts = count_records_select('log', $select)) {
2159 $count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)');
2160 return $count;
2162 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
2163 if ($count->attempts = count_records_select('log', $select .' AND info = \''. $username .'\'')) {
2164 return $count;
2167 return NULL;
2171 /// GENERAL HELPFUL THINGS ///////////////////////////////////
2174 * Dump a given object's information in a PRE block.
2176 * Mostly just used for debugging.
2178 * @param mixed $object The data to be printed
2180 function print_object($object) {
2181 echo '<pre class="notifytiny">' . htmlspecialchars(print_r($object,true)) . '</pre>';
2185 * Check whether a course is visible through its parents
2186 * path.
2188 * Notes:
2190 * - All we need from the course is ->category. _However_
2191 * if the course object has a categorypath property,
2192 * we'll save a dbquery
2194 * - If we return false, you'll still need to check if
2195 * the user can has the 'moodle/category:viewhiddencategories'
2196 * capability...
2198 * - Will generate 2 DB calls.
2200 * - It does have a small local cache, however...
2202 * - Do NOT call this over many courses as it'll generate
2203 * DB traffic. Instead, see what get_my_courses() does.
2205 * @param mixed $object A course object
2206 * @return bool
2208 function course_parent_visible($course = null) {
2209 global $CFG;
2210 //return true;
2211 static $mycache;
2213 if (!is_object($course)) {
2214 return true;
2216 if (!empty($CFG->allowvisiblecoursesinhiddencategories)) {
2217 return true;
2220 if (!isset($mycache)) {
2221 $mycache = array();
2222 } else {
2223 // cast to force assoc array
2224 $k = (string)$course->category;
2225 if (isset($mycache[$k])) {
2226 return $mycache[$k];
2230 if (isset($course->categorypath)) {
2231 $path = $course->categorypath;
2232 } else {
2233 $path = get_field('course_categories', 'path',
2234 'id', $course->category);
2236 $catids = substr($path,1); // strip leading slash
2237 $catids = str_replace('/',',',$catids);
2239 $sql = "SELECT MIN(visible)
2240 FROM {$CFG->prefix}course_categories
2241 WHERE id IN ($catids)";
2242 $vis = get_field_sql($sql);
2244 // cast to force assoc array
2245 $k = (string)$course->category;
2246 $mycache[$k] = $vis;
2248 return $vis;
2252 * This function is the official hook inside XMLDB stuff to delegate its debug to one
2253 * external function.
2255 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
2256 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
2258 * @param $message string contains the error message
2259 * @param $object object XMLDB object that fired the debug
2261 function xmldb_debug($message, $object) {
2263 debugging($message, DEBUG_DEVELOPER);
2267 * true or false function to see if user can create any courses at all
2268 * @return bool
2270 function user_can_create_courses() {
2271 global $USER;
2272 // if user has course creation capability at any site or course cat, then return true;
2274 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM))) {
2275 return true;
2277 if ($cats = get_records('course_categories')) {
2278 foreach ($cats as $cat) {
2279 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) {
2280 return true;
2284 return false;
2287 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: