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
15 * Escape all dangerous characters in a data record
17 * $dataobject is an object containing needed data
18 * Run over each field exectuting addslashes() function
19 * to escape SQL unfriendly characters (e.g. quotes)
20 * Handy when writing back data read from the database
22 * @param $dataobject Object containing the database record
23 * @return object Same object with neccessary characters escaped
25 function addslashes_object( $dataobject ) {
26 $a = get_object_vars( $dataobject);
27 foreach ($a as $key=>$value) {
28 $a[$key] = addslashes( $value );
33 /// USER DATABASE ////////////////////////////////////////////////
36 * Returns $user object of the main admin user
37 * primary admin = admin with lowest role_assignment id among admins
39 * @return object(admin) An associative array representing the admin user.
41 function get_admin () {
46 if (isset($myadmin)) {
50 if ( $admins = get_admins() ) {
51 foreach ($admins as $admin) {
53 return $admin; // ie the first one
61 * Returns list of all admins
66 function get_admins() {
70 $context = get_context_instance(CONTEXT_SYSTEM
, SITEID
);
72 return get_users_by_capability($context, 'moodle/site:doanything', 'u.*, ra.id as adminid', 'ra.id ASC'); // only need first one
77 function get_courses_in_metacourse($metacourseid) {
80 $sql = "SELECT c.id,c.shortname,c.fullname FROM {$CFG->prefix}course c, {$CFG->prefix}course_meta mc WHERE mc.parent_course = $metacourseid
81 AND mc.child_course = c.id ORDER BY c.shortname";
83 return get_records_sql($sql);
86 function get_courses_notin_metacourse($metacourseid,$count=false) {
91 $sql = "SELECT COUNT(c.id)";
93 $sql = "SELECT c.id,c.shortname,c.fullname";
96 $alreadycourses = get_courses_in_metacourse($metacourseid);
98 $sql .= " FROM {$CFG->prefix}course c WHERE ".((!empty($alreadycourses)) ?
"c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
99 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID
." and c.metacourse != 1 ".((empty($count)) ?
" ORDER BY c.shortname" : "");
101 return get_records_sql($sql);
104 function count_courses_notin_metacourse($metacourseid) {
107 $alreadycourses = get_courses_in_metacourse($metacourseid);
109 $sql = "SELECT COUNT(c.id) AS notin FROM {$CFG->prefix}course c
110 WHERE ".((!empty($alreadycourses)) ?
"c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
111 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID
." and c.metacourse != 1";
113 if (!$count = get_record_sql($sql)) {
117 return $count->notin
;
121 * Search through course users
123 * If $coursid specifies the site course then this function searches
124 * through all undeleted and confirmed users
128 * @param int $courseid The course in question.
129 * @param int $groupid The group in question.
130 * @param string $searchtext ?
131 * @param string $sort ?
132 * @param string $exceptions ?
135 function search_users($courseid, $groupid, $searchtext, $sort='', $exceptions='') {
139 $fullname = sql_fullname('u.firstname', 'u.lastname');
141 if (!empty($exceptions)) {
142 $except = ' AND u.id NOT IN ('. $exceptions .') ';
148 $order = ' ORDER BY '. $sort;
153 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
155 if (!$courseid or $courseid == SITEID
) {
156 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
157 FROM {$CFG->prefix}user u
159 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
164 //TODO:check. Remove group DB dependencies.
165 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
166 FROM {$CFG->prefix}user u,
167 {$CFG->prefix}groups_members gm
168 WHERE $select AND gm.groupid = '$groupid' AND gm.userid = u.id
169 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
172 $context = get_context_instance(CONTEXT_COURSE
, $courseid);
173 $contextlists = get_related_contexts_string($context);
174 $users = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
175 FROM {$CFG->prefix}user u,
176 {$CFG->prefix}role_assignments ra
177 WHERE $select AND ra.contextid $contextlists AND ra.userid = u.id
178 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
187 * Returns a list of all site users
188 * Obsolete, just calls get_course_users(SITEID)
191 * @deprecated Use {@link get_course_users()} instead.
192 * @param string $fields A comma separated list of fields to be returned from the chosen table.
193 * @return object|false {@link $USER} records or false if error.
195 function get_site_users($sort='u.lastaccess DESC', $fields='*', $exceptions='') {
197 return get_course_users(SITEID
, $sort, $exceptions, $fields);
202 * Returns a subset of users
205 * @param bool $get If false then only a count of the records is returned
206 * @param string $search A simple string to search for
207 * @param bool $confirmed A switch to allow/disallow unconfirmed users
208 * @param array(int) $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
209 * @param string $sort A SQL snippet for the sorting criteria to use
210 * @param string $firstinitial ?
211 * @param string $lastinitial ?
212 * @param string $page ?
213 * @param string $recordsperpage ?
214 * @param string $fields A comma separated list of fields to be returned from the chosen table.
215 * @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.
217 function get_users($get=true, $search='', $confirmed=false, $exceptions='', $sort='firstname ASC',
218 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*') {
222 if ($get && !$recordsperpage) {
223 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
224 'On large installations, this will probably cause an out of memory error. ' .
225 'Please think again and change your code so that it does not try to ' .
226 'load so much data into memory.', DEBUG_DEVELOPER
);
230 $fullname = sql_fullname();
232 $select = 'username <> \'guest\' AND deleted = 0';
234 if (!empty($search)){
235 $search = trim($search);
236 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
240 $select .= ' AND confirmed = \'1\' ';
244 $select .= ' AND id NOT IN ('. $exceptions .') ';
248 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\'';
251 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\'';
255 return get_records_select('user', $select, $sort, $fields, $page, $recordsperpage);
257 return count_records_select('user', $select);
263 * shortdesc (optional)
268 * @param string $sort ?
269 * @param string $dir ?
270 * @param int $categoryid ?
271 * @param int $categoryid ?
272 * @param string $search ?
273 * @param string $firstinitial ?
274 * @param string $lastinitial ?
275 * @returnobject {@link $USER} records
276 * @todo Finish documenting this function
279 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
280 $search='', $firstinitial='', $lastinitial='', $remotewhere='') {
285 $fullname = sql_fullname();
287 $select = "deleted <> '1'";
289 if (!empty($search)) {
290 $search = trim($search);
291 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%' OR username='$search') ";
295 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\' ';
299 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\' ';
302 $select .= $remotewhere;
305 $sort = ' ORDER BY '. $sort .' '. $dir;
308 /// warning: will return UNCONFIRMED USERS
309 return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
310 FROM {$CFG->prefix}user
311 WHERE $select $sort", $page, $recordsperpage);
317 * Full list of users that have confirmed their accounts.
322 function get_users_confirmed() {
324 return get_records_sql("SELECT *
325 FROM {$CFG->prefix}user
328 AND username <> 'guest'");
333 * Full list of users that have not yet confirmed their accounts.
336 * @param string $cutofftime ?
337 * @return object {@link $USER} records
339 function get_users_unconfirmed($cutofftime=2000000000) {
341 return get_records_sql("SELECT *
342 FROM {$CFG->prefix}user
345 AND firstaccess < $cutofftime");
349 * All users that we have not seen for a really long time (ie dead accounts)
352 * @param string $cutofftime ?
353 * @return object {@link $USER} records
355 function get_users_longtimenosee($cutofftime) {
357 return get_records_sql("SELECT userid as id, courseid
358 FROM {$CFG->prefix}user_lastaccess
359 WHERE courseid != ".SITEID
."
361 AND timeaccess < $cutofftime ");
365 * Full list of bogus accounts that are probably not ever going to be used
368 * @param string $cutofftime ?
369 * @return object {@link $USER} records
372 function get_users_not_fully_set_up($cutofftime=2000000000) {
374 return get_records_sql("SELECT *
375 FROM {$CFG->prefix}user
378 AND lastaccess < $cutofftime
380 AND (lastname = '' OR firstname = '' OR email = '')");
383 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
387 * Returns $course object of the top-level site.
389 * @return course A {@link $COURSE} object for the site
391 function get_site() {
395 if (!empty($SITE->id
)) { // We already have a global to use, so return that
399 if ($course = get_record('course', 'category', 0)) {
407 * Returns list of courses, for whole site, or category
409 * Returns list of courses, for whole site, or category
410 * Important: Using c.* for fields is extremely expensive because
411 * we are using distinct. You almost _NEVER_ need all the fields
412 * in such a large SELECT
414 * @param type description
417 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
421 if ($categoryid != "all" && is_numeric($categoryid)) {
422 $categoryselect = "WHERE c.category = '$categoryid'";
424 $categoryselect = "";
430 $sortstatement = "ORDER BY $sort";
433 $visiblecourses = array();
435 // pull out all course matching the cat
436 if ($courses = get_records_sql("SELECT $fields
437 FROM {$CFG->prefix}course c
441 // loop throught them
442 foreach ($courses as $course) {
444 if (isset($course->visible
) && $course->visible
<= 0) {
445 // for hidden courses, require visibility check
446 if (has_capability('moodle/course:viewhiddencourses',
447 get_context_instance(CONTEXT_COURSE
, $course->id
))) {
448 $visiblecourses [] = $course;
451 $visiblecourses [] = $course;
455 return $visiblecourses;
459 $visiblecourses = "";
461 if (!empty($categoryselect)) {
464 if (!empty($USER->id)) { // May need to check they are a teacher
465 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
466 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
467 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course = c.id";
470 $visiblecourses = "$sqland c.visible > 0";
473 if ($categoryselect or $visiblecourses) {
474 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
476 $selectsql = "{$CFG->prefix}course c $teachertable";
479 $extrafield = str_replace('ASC','',$sort);
480 $extrafield = str_replace('DESC','',$extrafield);
481 $extrafield = trim($extrafield);
482 if (!empty($extrafield)) {
483 $extrafield = ','.$extrafield;
485 return get_records_sql("SELECT ".((!empty($teachertable)) ? " DISTINCT " : "")." $fields $extrafield FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : ""));
491 * Returns list of courses, for whole site, or category
493 * Similar to get_courses, but allows paging
494 * Important: Using c.* for fields is extremely expensive because
495 * we are using distinct. You almost _NEVER_ need all the fields
496 * in such a large SELECT
498 * @param type description
501 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
502 &$totalcount, $limitfrom="", $limitnum="") {
506 $categoryselect = "";
507 if ($categoryid != "all" && is_numeric($categoryid)) {
508 $categoryselect = "WHERE c.category = '$categoryid'";
510 $categoryselect = "";
513 // pull out all course matching the cat
514 $visiblecourses = array();
515 if (!($rs = get_recordset_sql("SELECT $fields,
516 ctx.id AS ctxid, ctx.path AS ctxpath,
517 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
518 FROM {$CFG->prefix}course c
519 JOIN {$CFG->prefix}context ctx
520 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
523 return $visiblecourses;
528 $limitnum = $rs->RecordCount();
535 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
536 if ($rs->RecordCount()) {
537 while ($course = rs_fetch_next_record($rs)) {
538 $course = make_context_subobj($course);
539 if ($course->visible
<= 0) {
540 // for hidden courses, require visibility check
541 if (has_capability('moodle/course:viewhiddencourses', $course->context
)) {
543 if ($totalcount > $limitfrom && count($visiblecourses) < $limitnum) {
544 $visiblecourses [] = $course;
549 if ($totalcount > $limitfrom && count($visiblecourses) < $limitnum) {
550 $visiblecourses [] = $course;
555 return $visiblecourses;
559 $categoryselect = "";
560 if ($categoryid != "all" && is_numeric($categoryid)) {
561 $categoryselect = "c.category = '$categoryid'";
565 $visiblecourses = "";
567 if (!empty($categoryselect)) {
570 if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
571 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
572 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
573 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
576 $visiblecourses = "$sqland c.visible > 0";
579 if ($limitfrom !== "") {
580 $limit = sql_paging_limit($limitfrom, $limitnum);
585 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
587 $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
589 return get_records_sql("SELECT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
594 * Retrieve course records with the course managers and other related records
595 * that we need for print_course(). This allows print_courses() to do its job
596 * in a constant number of DB queries, regardless of the number of courses,
597 * role assignments, etc.
599 * The returned array is indexed on c.id, and each course will have
600 * - $course->context - a context obj
601 * - $course->managers - array containing RA objects that include a $user obj
602 * with the minimal fields needed for fullname()
605 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
609 * - Grab the courses JOINed w/context
611 * - Grab the interesting course-manager RAs
612 * JOINed with a base user obj and add them to each course
614 * So as to do all the work in 2 DB queries. The RA+user JOIN
615 * ends up being pretty expensive if it happens over _all_
616 * courses on a large site. (Are we surprised!?)
618 * So this should _never_ get called with 'all' on a large site.
623 $allcats = false; // bool flag
624 if ($categoryid === 'all') {
625 $categoryclause = '';
627 } elseif (is_numeric($categoryid)) {
628 $categoryclause = "c.category = $categoryid";
630 debugging("Could not recognise categoryid = $categoryid");
631 $categoryclause = '';
634 $basefields = array('id', 'category', 'sortorder',
635 'shortname', 'fullname', 'idnumber',
636 'teacher', 'teachers', 'student', 'students',
637 'guest', 'startdate', 'visible',
638 'newsitems', 'cost', 'enrol',
639 'groupmode', 'groupmodeforce');
641 if (!is_null($fields) && is_string($fields)) {
642 if (empty($fields)) {
643 $fields = $basefields;
645 // turn the fields from a string to an array that
646 // get_user_courses_bycap() will like...
647 $fields = explode(',',$fields);
648 $fields = array_map('trim', $fields);
649 $fields = array_unique(array_merge($basefields, $fields));
651 } elseif (is_array($fields)) {
652 $fields = array_merge($basefields,$fields);
654 $coursefields = 'c.' .join(',c.', $fields);
659 $sortstatement = "ORDER BY $sort";
662 $where = 'WHERE c.id != ' . SITEID
;
663 if ($categoryclause !== ''){
664 $where = "$where AND $categoryclause";
667 // pull out all courses matching the cat
668 $sql = "SELECT $coursefields,
669 ctx.id AS ctxid, ctx.path AS ctxpath,
670 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
671 FROM {$CFG->prefix}course c
672 JOIN {$CFG->prefix}context ctx
673 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
679 if ($courses = get_records_sql($sql)) {
680 // loop on courses materialising
681 // the context, and prepping data to fetch the
682 // managers efficiently later...
683 foreach ($courses as $k => $course) {
684 $courses[$k] = make_context_subobj($courses[$k]);
685 $courses[$k]->managers
= array();
686 if ($allcats === false) {
687 // single cat, so take just the first one...
688 if ($catpath === NULL) {
689 $catpath = preg_replace(':/\d+$:', '',$courses[$k]->context
->path
);
692 // chop off the contextid of the course itself
693 // like dirname() does...
694 $catpaths[] = preg_replace(':/\d+$:', '',$courses[$k]->context
->path
);
698 return array(); // no courses!
701 $CFG->coursemanager
= trim($CFG->coursemanager
);
702 if (empty($CFG->coursemanager
)) {
706 $managerroles = split(',', $CFG->coursemanager
);
708 if (count($managerroles)) {
709 if ($allcats === true) {
710 $catpaths = array_unique($catpaths);
712 foreach ($catpaths as $cpath) {
713 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
715 $ctxids = array_unique($ctxids);
716 $catctxids = implode( ',' , $ctxids);
717 unset($catpaths);unset($cpath);
719 // take the ctx path from the first course
720 // as all categories will be the same...
721 $catpath = substr($catpath,1);
722 $catpath = preg_replace(':/\d+$:','',$catpath);
723 $catctxids = str_replace('/',',',$catpath);
725 if ($categoryclause !== '') {
726 $categoryclause = "AND $categoryclause";
729 * Note: Here we use a LEFT OUTER JOIN that can
730 * "optionally" match to avoid passing a ton of context
731 * ids in an IN() clause. Perhaps a subselect is faster.
733 * In any case, this SQL is not-so-nice over large sets of
734 * courses with no $categoryclause.
737 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
739 r.id AS roleid, r.name as rolename,
740 u.id AS userid, u.firstname, u.lastname
741 FROM {$CFG->prefix}role_assignments ra
742 JOIN {$CFG->prefix}context ctx
743 ON ra.contextid = ctx.id
744 JOIN {$CFG->prefix}user u
746 JOIN {$CFG->prefix}role r
748 LEFT OUTER JOIN {$CFG->prefix}course c
749 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE
.")
750 WHERE ( c.id IS NOT NULL
751 OR ra.contextid IN ($catctxids) )
752 AND ra.roleid IN ({$CFG->coursemanager})
754 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
756 $rs = get_recordset_sql($sql);
758 // This loop is fairly stupid as it stands - might get better
759 // results doing an initial pass clustering RAs by path.
760 if ($rs->RecordCount()) {
761 while ($ra = rs_fetch_next_record($rs)) {
762 $user = new StdClass
;
763 $user->id
= $ra->userid
; unset($ra->userid
);
764 $user->firstname
= $ra->firstname
; unset($ra->firstname
);
765 $user->lastname
= $ra->lastname
; unset($ra->lastname
);
767 if ($ra->contextlevel
== CONTEXT_SYSTEM
) {
768 foreach ($courses as $k => $course) {
769 $courses[$k]->managers
[] = $ra;
771 } elseif ($ra->contextlevel
== CONTEXT_COURSECAT
) {
772 if ($allcats === false) {
774 foreach ($courses as $k => $course) {
775 $courses[$k]->managers
[] = $ra;
778 foreach ($courses as $k => $course) {
779 // Note that strpos() returns 0 as "matched at pos 0"
780 if (strpos($course->context
->path
, $ra->path
.'/')===0) {
781 // Only add it to subpaths
782 $courses[$k]->managers
[] = $ra;
786 } else { // course-level
787 $courses[$ra->instanceid
]->managers
[] = $ra;
800 * Convenience function - lists courses that a user has access to view.
802 * For admins and others with access to "every" course in the system, we should
803 * try to get courses with explicit RAs.
805 * NOTE: this function is heavily geared towards the perspective of the user
806 * passed in $userid. So it will hide courses that the user cannot see
807 * (for any reason) even if called from cron or from another $USER's
810 * If you really want to know what courses are assigned to the user,
811 * without any hiding or scheming, call the lower-level
812 * get_user_courses_bycap().
815 * Notes inherited from get_user_courses_bycap():
817 * - $fields is an array of fieldnames to ADD
818 * so name the fields you really need, which will
819 * be added and uniq'd
821 * - the course records have $c->context which is a fully
822 * valid context object. Saves you a query per course!
825 * @param int $userid The user of interest
826 * @param string $sort the sortorder in the course table
827 * @param array $fields - names of _additional_ fields to return (also accepts a string)
828 * @param bool $doanything True if using the doanything flag
829 * @param int $limit Maximum number of records to return, or 0 for unlimited
830 * @return array {@link $COURSE} of course objects
832 function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
836 // Guest's do not have any courses
837 $sitecontext = get_context_instance(CONTEXT_SYSTEM
, SITEID
);
838 if (has_capability('moodle/legacy:guest',$sitecontext,$userid,false)) {
842 $basefields = array('id', 'category', 'sortorder',
843 'shortname', 'fullname', 'idnumber',
844 'teacher', 'teachers', 'student', 'students',
845 'guest', 'startdate', 'visible',
846 'newsitems', 'cost', 'enrol',
847 'groupmode', 'groupmodeforce');
849 if (!is_null($fields) && is_string($fields)) {
850 if (empty($fields)) {
851 $fields = $basefields;
853 // turn the fields from a string to an array that
854 // get_user_courses_bycap() will like...
855 $fields = explode(',',$fields);
856 $fields = array_map('trim', $fields);
857 $fields = array_unique(array_merge($basefields, $fields));
859 } elseif (is_array($fields)) {
860 $fields = array_unique(array_merge($basefields, $fields));
862 $fields = $basefields;
868 $orderby = "ORDER BY $sort";
872 // Logged-in user - Check cached courses
874 // NOTE! it's a _string_ because
875 // - it's all we'll ever use
876 // - it serialises much more compact than an array
877 // this a big concern here - cost of serialise
878 // and unserialise gets huge as the session grows
880 // If the courses are too many - it won't be set
881 // for large numbers of courses, caching in the session
882 // has marginal benefits (costs too much, not
883 // worthwhile...) and we may hit SQL parser limits
884 // because we use IN()
886 if ($userid === $USER->id
) {
887 if (isset($USER->loginascontext
)
888 && $USER->loginascontext
->contextlevel
== CONTEXT_COURSE
) {
889 // list _only_ this course
890 // anything else is asking for trouble...
891 $courseids = $USER->loginascontext
->instanceid
;
892 } elseif (isset($USER->mycourses
)
893 && is_string($USER->mycourses
)) {
894 if ($USER->mycourses
=== '') {
895 // empty str means: user has no courses
896 // ... so do the easy thing...
899 $courseids = $USER->mycourses
;
902 if (isset($courseids)) {
903 // The data massaging here MUST be kept in sync with
904 // get_user_courses_bycap() so we return
906 // (but here we don't need to check has_cap)
907 $coursefields = 'c.' .join(',c.', $fields);
908 $sql = "SELECT $coursefields,
909 ctx.id AS ctxid, ctx.path AS ctxpath,
910 ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel,
911 cc.path AS categorypath
912 FROM {$CFG->prefix}course c
913 JOIN {$CFG->prefix}course_categories cc
915 JOIN {$CFG->prefix}context ctx
916 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
917 WHERE c.id IN ($courseids)
919 $rs = get_recordset_sql($sql);
921 $cc = 0; // keep count
922 if ($rs->RecordCount()) {
923 while ($c = rs_fetch_next_record($rs)) {
924 // build the context obj
925 $c = make_context_subobj($c);
927 $courses[$c->id
] = $c;
928 if ($limit > 0 && $cc++
> $limit) {
938 // Non-cached - get accessinfo
939 if ($userid === $USER->id
&& isset($USER->access
)) {
940 $accessinfo = $USER->access
;
942 $accessinfo = get_user_access_sitewide($userid);
946 $courses = get_user_courses_bycap($userid, 'moodle/course:view', $accessinfo,
947 $doanything, $sort, $fields,
951 // If we have to walk category visibility
952 // to eval course visibility, get the categories
953 if (empty($CFG->allowvisiblecoursesinhiddencategories
)) {
954 $sql = "SELECT cc.id, cc.path, cc.visible,
955 ctx.id AS ctxid, ctx.path AS ctxpath,
956 ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel
957 FROM {$CFG->prefix}course_categories cc
958 JOIN {$CFG->prefix}context ctx
959 ON (cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
.")
961 $rs = get_recordset_sql($sql);
963 // Using a temporary array instead of $cats here, to avoid a "true" result when isnull($cats) further down
964 $categories = array();
965 if ($rs->RecordCount()) {
966 while ($course_cat = rs_fetch_next_record($rs)) {
967 // build the context obj
968 $course_cat = make_context_subobj($course_cat);
969 $categories[$course_cat->id
] = $course_cat;
973 if (!empty($categories)) {
981 // Strangely, get_my_courses() is expected to return the
982 // array keyed on id, which messes up the sorting
983 // So do that, and also cache the ids in the session if appropriate
986 $courses_count = count($courses);
988 $vcatpaths = array();
989 if ($userid === $USER->id
&& $courses_count < 500) {
992 for ($n=0; $n<$courses_count; $n++
) {
995 // Check whether $USER (not $userid) can _actually_ see them
996 // Easy if $CFG->allowvisiblecoursesinhiddencategories
997 // is set, and we don't have to care about categories.
998 // Lots of work otherwise... (all in mem though!)
1001 if (is_null($cats)) { // easy rules!
1002 if ($courses[$n]->visible
== true) {
1004 } elseif (has_capability('moodle/course:viewhiddencourses',
1005 $courses[$n]->context
, $USER->id
)) {
1010 // Is the cat visible?
1011 // we have to assume it _is_ visible
1012 // so we can shortcut when we find a hidden one
1015 $cpath = $courses[$n]->categorypath
;
1016 if (isset($vcatpaths[$cpath])) {
1017 $viscat = $vcatpaths[$cpath];
1019 $cpath = substr($cpath,1); // kill leading slash
1020 $cpath = explode('/',$cpath);
1021 $ccct = count($cpath);
1022 for ($m=0;$m<$ccct;$m++
) {
1024 if ($cats[$ccid]->visible
==false) {
1029 $vcatpaths[$courses[$n]->categorypath
] = $viscat;
1033 // Perhaps it's actually visible to $USER
1034 // check moodle/category:visibility
1036 // The name isn't obvious, but the description says
1037 // "See hidden categories" so the user shall see...
1038 // But also check if the allowvisiblecoursesinhiddencategories setting is true, and check for course visibility
1039 if ($viscat === false) {
1040 $catctx = $cats[$courses[$n]->category
]->context
;
1041 if (has_capability('moodle/category:visibility', $catctx, $USER->id
)) {
1042 $vcatpaths[$courses[$n]->categorypath
] = true;
1044 } elseif ($CFG->allowvisiblecoursesinhiddencategories
&& $courses[$n]->visible
== true) {
1052 if ($viscat === true) {
1053 if ($courses[$n]->visible
== true) {
1055 } elseif (has_capability('moodle/course:viewhiddencourses',
1056 $courses[$n]->context
, $USER->id
)) {
1061 if ($cansee === true) {
1062 $kcourses[$courses[$n]->id
] = $courses[$n];
1063 if (is_array($cacheids)) {
1064 $cacheids[] = $courses[$n]->id
;
1068 if (is_array($cacheids)) {
1070 // - for the logged in user
1071 // - below the threshold (500)
1072 // empty string is _valid_
1073 $USER->mycourses
= join(',',$cacheids);
1074 } elseif ($userid === $USER->id
&& isset($USER->mycourses
)) {
1075 // cheap sanity check
1076 unset($USER->mycourses
);
1083 * A list of courses that match a search
1086 * @param array $searchterms ?
1087 * @param string $sort ?
1088 * @param int $page ?
1089 * @param int $recordsperpage ?
1090 * @param int $totalcount Passed in by reference. ?
1091 * @return object {@link $COURSE} records
1093 function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
1097 //to allow case-insensitive search for postgesql
1098 if ($CFG->dbfamily
== 'postgres') {
1100 $NOTLIKE = 'NOT ILIKE'; // case-insensitive
1105 $NOTLIKE = 'NOT LIKE';
1107 $NOTREGEXP = 'NOT REGEXP';
1110 $fullnamesearch = '';
1111 $summarysearch = '';
1113 foreach ($searchterms as $searchterm) {
1115 /// Under Oracle and MSSQL, trim the + and - operators and perform
1116 /// simpler LIKE search
1117 if ($CFG->dbfamily
== 'oracle' ||
$CFG->dbfamily
== 'mssql') {
1118 $searchterm = trim($searchterm, '+-');
1121 if ($fullnamesearch) {
1122 $fullnamesearch .= ' AND ';
1124 if ($summarysearch) {
1125 $summarysearch .= ' AND ';
1128 if (substr($searchterm,0,1) == '+') {
1129 $searchterm = substr($searchterm,1);
1130 $summarysearch .= " c.summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
1131 $fullnamesearch .= " c.fullname $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]|$)' ";
1137 $summarysearch .= ' c.summary '. $LIKE .' \'%'. $searchterm .'%\' ';
1138 $fullnamesearch .= ' c.fullname '. $LIKE .' \'%'. $searchterm .'%\' ';
1144 ctx.id AS ctxid, ctx.path AS ctxpath,
1145 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1146 FROM {$CFG->prefix}course c
1147 JOIN {$CFG->prefix}context ctx
1148 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
1149 WHERE ( $fullnamesearch OR $summarysearch )
1155 if ($rs = get_recordset_sql($sql)) {
1159 $limitfrom = $page * $recordsperpage;
1160 $limitto = $limitfrom +
$recordsperpage;
1161 $c = 0; // counts how many visible courses we've seen
1163 while ($course = rs_fetch_next_record($rs)) {
1164 $course = make_context_subobj($course);
1165 if ($course->visible ||
has_capability('moodle/course:viewhiddencourses', $course->context
)) {
1166 // Don't exit this loop till the end
1167 // we need to count all the visible courses
1168 // to update $totalcount
1169 if ($c >= $limitfrom && $c < $limitto) {
1170 $courses[] = $course;
1177 // our caller expects 2 bits of data - our return
1178 // array, and an updated $totalcount
1185 * Returns a sorted list of categories. Each category object has a context
1186 * property that is a context object.
1188 * When asking for $parent='none' it will return all the categories, regardless
1189 * of depth. Wheen asking for a specific parent, the default is to return
1190 * a "shallow" resultset. Pass false to $shallow and it will return all
1191 * the child categories as well.
1194 * @param string $parent The parent category if any
1195 * @param string $sort the sortorder
1196 * @param bool $shallow - set to false to get the children too
1197 * @return array of categories
1199 function get_categories($parent='none', $sort=NULL, $shallow=true) {
1202 if ($sort === NULL) {
1203 $sort = 'ORDER BY cc.sortorder ASC';
1204 } elseif ($sort ==='') {
1205 // leave it as empty
1207 $sort = "ORDER BY $sort";
1210 if ($parent === 'none') {
1211 $sql = "SELECT cc.*,
1212 ctx.id AS ctxid, ctx.path AS ctxpath,
1213 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1214 FROM {$CFG->prefix}course_categories cc
1215 JOIN {$CFG->prefix}context ctx
1216 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
."
1218 } elseif ($shallow) {
1219 $parent = (int)$parent;
1220 $sql = "SELECT cc.*,
1221 ctx.id AS ctxid, ctx.path AS ctxpath,
1222 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1223 FROM {$CFG->prefix}course_categories cc
1224 JOIN {$CFG->prefix}context ctx
1225 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
."
1226 WHERE cc.parent=$parent
1229 $parent = (int)$parent;
1230 $sql = "SELECT cc.*,
1231 ctx.id AS ctxid, ctx.path AS ctxpath,
1232 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1233 FROM {$CFG->prefix}course_categories cc
1234 JOIN {$CFG->prefix}context ctx
1235 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
."
1236 JOIN {$CFG->prefix}course_categories ccp
1237 ON (cc.path LIKE ".sql_concat('ccp.path',"'%'").")
1238 WHERE ccp.id=$parent
1241 $categories = array();
1243 if( $rs = get_recordset_sql($sql) ){
1244 while ($cat = rs_fetch_next_record($rs)) {
1245 $cat = make_context_subobj($cat);
1246 if ($cat->visible ||
has_capability('moodle/course:create',$cat->context
)) {
1247 $categories[$cat->id
] = $cat;
1256 * Returns an array of category ids of all the subcategories for a given
1258 * @param $catid - The id of the category whose subcategories we want to find.
1259 * @return array of category ids.
1261 function get_all_subcategories($catid) {
1265 if ($categories = get_records('course_categories', 'parent', $catid)) {
1266 foreach ($categories as $cat) {
1267 array_push($subcats, $cat->id
);
1268 $subcats = array_merge($subcats, get_all_subcategories($cat->id
));
1276 * This recursive function makes sure that the courseorder is consecutive
1278 * @param type description
1280 * $n is the starting point, offered only for compatilibity -- will be ignored!
1281 * $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
1282 * safely from 1.4 to 1.5
1284 function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
1290 $catgap = 1000; // "standard" category gap
1291 $tolerance = 200; // how "close" categories can get
1293 if ($categoryid > 0){
1294 // update depth and path
1295 $cat = get_record('course_categories', 'id', $categoryid);
1296 if ($cat->parent
== 0) {
1299 } else if ($depth == 0 ) { // doesn't make sense; get from DB
1300 // this is only called if the $depth parameter looks dodgy
1301 $parent = get_record('course_categories', 'id', $cat->parent
);
1302 $path = $parent->path
;
1303 $depth = $parent->depth
;
1305 $path = $path . '/' . $categoryid;
1306 $depth = $depth +
1;
1308 if ($cat->path
!== $path) {
1309 set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
1311 if ($cat->depth
!= $depth) {
1312 set_field('course_categories', 'depth', $depth, 'id', $categoryid);
1316 // get some basic info about courses in the category
1317 $info = get_record_sql('SELECT MIN(sortorder) AS min,
1318 MAX(sortorder) AS max,
1319 COUNT(sortorder) AS count
1320 FROM ' . $CFG->prefix
. 'course
1321 WHERE category=' . $categoryid);
1322 if (is_object($info)) { // no courses?
1324 $count = $info->count
;
1329 if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
1333 // $hasgap flag indicates whether there's a gap in the sequence
1335 if ($max-$min+
1 != $count) {
1339 // $mustshift indicates whether the sequence must be shifted to
1342 if ($min < $n+
$tolerance ||
$min > $n+
$tolerance+
$catgap ) {
1346 // actually sort only if there are courses,
1347 // and we meet one ofthe triggers:
1349 // - they are not in a continuos block
1350 // - they are too close to the 'bottom'
1351 if ($count && ( $safe ||
$hasgap ||
$mustshift ) ) {
1352 // special, optimized case where all we need is to shift
1353 if ( $mustshift && !$safe && !$hasgap) {
1354 $shift = $n +
$catgap - $min;
1355 if ($shift < $count) {
1356 $shift = $count +
$catgap;
1358 // UPDATE course SET sortorder=sortorder+$shift
1359 execute_sql("UPDATE {$CFG->prefix}course
1360 SET sortorder=sortorder+$shift
1361 WHERE category=$categoryid", 0);
1362 $n = $n +
$catgap +
$count;
1364 } else { // do it slowly
1366 // if the new sequence overlaps the current sequence, lack of transactions
1367 // will stop us -- shift things aside for a moment...
1368 if ($safe ||
($n >= $min && $n+
$count+
1 < $min && $CFG->dbfamily
==='mysql')) {
1369 $shift = $max +
$n +
1000;
1370 execute_sql("UPDATE {$CFG->prefix}course
1371 SET sortorder=sortorder+$shift
1372 WHERE category=$categoryid", 0);
1375 $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
1377 $tx = true; // transaction sanity
1378 foreach ($courses as $course) {
1379 if ($tx && $course->sortorder
!= $n ) { // save db traffic
1380 $tx = $tx && set_field('course', 'sortorder', $n,
1390 // if we failed when called with !safe, try
1391 // to recover calling self with safe=true
1392 return fix_course_sortorder($categoryid, $n, true, $depth, $path);
1397 set_field('course_categories', 'coursecount', $count, 'id', $categoryid);
1399 // $n could need updating
1400 $max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid");
1405 if ($categories = get_categories($categoryid)) {
1406 foreach ($categories as $category) {
1407 $n = fix_course_sortorder($category->id
, $n, $safe, $depth, $path);
1415 * Ensure all courses have a valid course category
1416 * useful if a category has been removed manually
1418 function fix_coursecategory_orphans() {
1422 // Note: the handling of sortorder here is arguably
1423 // open to race conditions. Hard to fix here, unlikely
1424 // to hit anyone in production.
1426 $sql = "SELECT c.id, c.category, c.shortname
1427 FROM {$CFG->prefix}course c
1428 LEFT OUTER JOIN {$CFG->prefix}course_categories cc ON c.category=cc.id
1429 WHERE cc.id IS NULL AND c.id != " . SITEID
;
1431 $rs = get_recordset_sql($sql);
1433 if ($rs->RecordCount()){ // we have some orphans
1435 // the "default" category is the lowest numbered...
1436 $default = get_field_sql("SELECT MIN(id)
1437 FROM {$CFG->prefix}course_categories");
1438 $sortorder = get_field_sql("SELECT MAX(sortorder)
1439 FROM {$CFG->prefix}course
1440 WHERE category=$default");
1445 while ($tx && $course = rs_fetch_next_record($rs)) {
1446 $tx = $tx && set_field('course', 'category', $default, 'id', $course->id
);
1447 $tx = $tx && set_field('course', 'sortorder', ++
$sortorder, 'id', $course->id
);
1458 * List of remote courses that a user has access to via MNET.
1459 * Works only on the IDP
1462 * @return array {@link $COURSE} of course objects
1464 function get_my_remotecourses($userid=0) {
1467 if (empty($userid)) {
1468 $userid = $USER->id
;
1471 $sql = "SELECT c.remoteid, c.shortname, c.fullname,
1472 c.hostid, c.summary, c.cat_name,
1474 FROM {$CFG->prefix}mnet_enrol_course c
1475 JOIN {$CFG->prefix}mnet_enrol_assignments a ON c.id=a.courseid
1476 JOIN {$CFG->prefix}mnet_host h ON c.hostid=h.id
1477 WHERE a.userid={$userid}";
1479 return get_records_sql($sql);
1483 * List of remote hosts that a user has access to via MNET.
1487 * @return array of host objects
1489 function get_my_remotehosts() {
1492 if ($USER->mnethostid
== $CFG->mnet_localhost_id
) {
1493 return false; // Return nothing on the IDP
1495 if (!empty($USER->mnet_foreign_host_array
) && is_array($USER->mnet_foreign_host_array
)) {
1496 return $USER->mnet_foreign_host_array
;
1502 * This function creates a default separated/connected scale
1504 * This function creates a default separated/connected scale
1505 * so there's something in the database. The locations of
1506 * strings and files is a bit odd, but this is because we
1507 * need to maintain backward compatibility with many different
1508 * existing language translations and older sites.
1512 function make_default_scale() {
1516 $defaultscale = NULL;
1517 $defaultscale->courseid
= 0;
1518 $defaultscale->userid
= 0;
1519 $defaultscale->name
= get_string('separateandconnected');
1520 $defaultscale->scale
= get_string('postrating1', 'forum').','.
1521 get_string('postrating2', 'forum').','.
1522 get_string('postrating3', 'forum');
1523 $defaultscale->timemodified
= time();
1525 /// Read in the big description from the file. Note this is not
1526 /// HTML (despite the file extension) but Moodle format text.
1527 $parentlang = get_string('parentlang');
1528 if (is_readable($CFG->dataroot
.'/lang/'. $CFG->lang
.'/help/forum/ratings.html')) {
1529 $file = file($CFG->dataroot
.'/lang/'. $CFG->lang
.'/help/forum/ratings.html');
1530 } else if (is_readable($CFG->dirroot
.'/lang/'. $CFG->lang
.'/help/forum/ratings.html')) {
1531 $file = file($CFG->dirroot
.'/lang/'. $CFG->lang
.'/help/forum/ratings.html');
1532 } else if ($parentlang and is_readable($CFG->dataroot
.'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1533 $file = file($CFG->dataroot
.'/lang/'. $parentlang .'/help/forum/ratings.html');
1534 } else if ($parentlang and is_readable($CFG->dirroot
.'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1535 $file = file($CFG->dirroot
.'/lang/'. $parentlang .'/help/forum/ratings.html');
1536 } else if (is_readable($CFG->dirroot
.'/lang/en_utf8/help/forum/ratings.html')) {
1537 $file = file($CFG->dirroot
.'/lang/en_utf8/help/forum/ratings.html');
1542 $defaultscale->description
= addslashes(implode('', $file));
1544 if ($defaultscale->id
= insert_record('scale', $defaultscale)) {
1545 execute_sql('UPDATE '. $CFG->prefix
.'forum SET scale = \''. $defaultscale->id
.'\'', false);
1551 * Returns a menu of all available scales from the site as well as the given course
1554 * @param int $courseid The id of the course as found in the 'course' table.
1557 function get_scales_menu($courseid=0) {
1561 $sql = "SELECT id, name FROM {$CFG->prefix}scale
1562 WHERE courseid = '0' or courseid = '$courseid'
1563 ORDER BY courseid ASC, name ASC";
1565 if ($scales = get_records_sql_menu($sql)) {
1569 make_default_scale();
1571 return get_records_sql_menu($sql);
1577 * Given a set of timezone records, put them in the database, replacing what is there
1580 * @param array $timezones An array of timezone records
1582 function update_timezone_records($timezones) {
1583 /// Given a set of timezone records, put them in the database
1587 /// Clear out all the old stuff
1588 execute_sql('TRUNCATE TABLE '.$CFG->prefix
.'timezone', false);
1590 /// Insert all the new stuff
1591 foreach ($timezones as $timezone) {
1592 insert_record('timezone', $timezone);
1597 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1600 * Just gets a raw list of all modules in a course
1603 * @param int $courseid The id of the course as found in the 'course' table.
1606 function get_course_mods($courseid) {
1609 if (empty($courseid)) {
1610 return false; // avoid warnings
1613 return get_records_sql("SELECT cm.*, m.name as modname
1614 FROM {$CFG->prefix}modules m,
1615 {$CFG->prefix}course_modules cm
1616 WHERE cm.course = '$courseid'
1617 AND cm.module = m.id ");
1622 * Given an id of a course module, finds the coursemodule description
1624 * @param string $modulename name of module type, eg. resource, assignment,...
1625 * @param int $cmid course module id (id in course_modules table)
1626 * @param int $courseid optional course id for extra validation
1627 * @return object course module instance with instance and module name
1629 function get_coursemodule_from_id($modulename, $cmid, $courseid=0) {
1633 $courseselect = ($courseid) ?
"cm.course = '$courseid' AND " : '';
1635 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1636 FROM {$CFG->prefix}course_modules cm,
1637 {$CFG->prefix}modules md,
1638 {$CFG->prefix}$modulename m
1641 cm.instance = m.id AND
1642 md.name = '$modulename' AND
1643 md.id = cm.module");
1647 * Given an instance number of a module, finds the coursemodule description
1649 * @param string $modulename name of module type, eg. resource, assignment,...
1650 * @param int $instance module instance number (id in resource, assignment etc. table)
1651 * @param int $courseid optional course id for extra validation
1652 * @return object course module instance with instance and module name
1654 function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
1658 $courseselect = ($courseid) ?
"cm.course = '$courseid' AND " : '';
1660 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1661 FROM {$CFG->prefix}course_modules cm,
1662 {$CFG->prefix}modules md,
1663 {$CFG->prefix}$modulename m
1665 cm.instance = m.id AND
1666 md.name = '$modulename' AND
1667 md.id = cm.module AND
1668 m.id = '$instance'");
1673 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1675 * Returns an array of all the active instances of a particular
1676 * module in given courses, sorted in the order they are defined
1677 * in the course. Returns false on any errors.
1680 * @param string $modulename The name of the module to get instances for
1681 * @param array $courses This depends on an accurate $course->modinfo
1682 * @return array of instances
1684 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1686 if (empty($courses) ||
!is_array($courses) ||
count($courses) == 0) {
1689 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode, cm.course
1690 FROM {$CFG->prefix}course_modules cm,
1691 {$CFG->prefix}course_sections cw,
1692 {$CFG->prefix}modules md,
1693 {$CFG->prefix}$modulename m
1694 WHERE cm.course IN (".implode(',',array_keys($courses)).") AND
1695 cm.instance = m.id AND
1696 cm.section = cw.id AND
1697 md.name = '$modulename' AND
1698 md.id = cm.module")) {
1702 $outputarray = array();
1704 foreach ($courses as $course) {
1705 if ($includeinvisible) {
1707 } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE
, $course->id
), $userid)) {
1708 // Usually hide non-visible instances from students
1714 /// Casting $course->modinfo to string prevents one notice when the field is null
1715 if (!$modinfo = unserialize((string)$course->modinfo
)) {
1718 foreach ($modinfo as $mod) {
1719 if ($mod->mod
== $modulename and $mod->visible
> $invisible) {
1720 $instance = $rawmods[$mod->cm
];
1721 if (!empty($mod->extra
)) {
1722 $instance->extra
= $mod->extra
;
1724 $outputarray[] = $instance;
1729 return $outputarray;
1734 * Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined
1736 * Returns an array of all the active instances of a particular
1737 * module in a given course, sorted in the order they are defined
1738 * in the course. Returns false on any errors.
1741 * @param string $modulename The name of the module to get instances for
1742 * @param object(course) $course This depends on an accurate $course->modinfo
1744 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1748 if (empty($course->modinfo
)) {
1752 if (!$modinfo = unserialize((string)$course->modinfo
)) {
1756 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode,cm.groupingid
1757 FROM {$CFG->prefix}course_modules cm,
1758 {$CFG->prefix}course_sections cw,
1759 {$CFG->prefix}modules md,
1760 {$CFG->prefix}$modulename m
1761 WHERE cm.course = '$course->id' AND
1762 cm.instance = m.id AND
1763 cm.section = cw.id AND
1764 md.name = '$modulename' AND
1765 md.id = cm.module")) {
1769 if ($includeinvisible) {
1771 } else if (has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_COURSE
, $course->id
), $userid)) {
1772 // Usually hide non-visible instances from students
1778 $outputarray = array();
1780 foreach ($modinfo as $mod) {
1781 $mod->id
= $mod->cm
;
1782 $mod->course
= $course->id
;
1783 if (!groups_course_module_visible($mod)) {
1786 if ($mod->mod
== $modulename and $mod->visible
> $invisible) {
1787 $instance = $rawmods[$mod->cm
];
1788 if (!empty($mod->extra
)) {
1789 $instance->extra
= $mod->extra
;
1791 $outputarray[] = $instance;
1795 return $outputarray;
1801 * Determine whether a module instance is visible within a course
1803 * Given a valid module object with info about the id and course,
1804 * and the module's type (eg "forum") returns whether the object
1808 * @param $moduletype Name of the module eg 'forum'
1809 * @param $module Object which is the instance of the module
1812 function instance_is_visible($moduletype, $module) {
1816 if (!empty($module->id
)) {
1817 if ($records = get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1818 FROM {$CFG->prefix}course_modules cm,
1819 {$CFG->prefix}modules m
1820 WHERE cm.course = '$module->course' AND
1821 cm.module = m.id AND
1822 m.name = '$moduletype' AND
1823 cm.instance = '$module->id'")) {
1825 foreach ($records as $record) { // there should only be one - use the first one
1826 return $record->visible
&& groups_course_module_visible($record);
1830 return true; // visible by default!
1836 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1840 * Add an entry to the log table.
1842 * Add an entry to the log table. These are "action" focussed rather
1843 * than web server hits, and provide a way to easily reconstruct what
1844 * any particular student has been doing.
1849 * @uses $REMOTE_ADDR
1851 * @param int $courseid The course id
1852 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
1853 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1854 * @param string $url The file and parameters used to see the results of the action
1855 * @param string $info Additional description information
1856 * @param string $cm The course_module->id if there is one
1857 * @param string $user If log regards $user other than $USER
1859 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1860 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1861 // This is for a good reason: it is the most frequently used DB update function,
1862 // so it has been optimised for speed.
1863 global $db, $CFG, $USER;
1865 if ($cm === '' ||
is_null($cm)) { // postgres won't translate empty string to its default
1872 if (!empty($USER->realuser
)) { // Don't log
1875 $userid = empty($USER->id
) ?
'0' : $USER->id
;
1878 $REMOTE_ADDR = getremoteaddr();
1881 $info = addslashes($info);
1882 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1883 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
1886 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
; $PERF->logwrites++
;};
1888 if ($CFG->type
= 'oci8po') {
1894 $result = $db->Execute('INSERT INTO '. $CFG->prefix
.'log (time, userid, course, ip, module, cmid, action, url, info)
1895 VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')");
1897 if (!$result and debugging()) {
1898 echo '<p>Error: Could not insert a new entry to the Moodle log</p>'; // Don't throw an error
1901 /// Store lastaccess times for the current user, do not use in cron and other commandline scripts
1902 /// only update the lastaccess/timeaccess fields only once every 60s
1903 if (!empty($USER->id
) && ($userid == $USER->id
) && !defined('FULLME')) {
1904 $res = $db->Execute('UPDATE '. $CFG->prefix
.'user
1905 SET lastip=\''. $REMOTE_ADDR .'\', lastaccess=\''. $timenow .'\'
1906 WHERE id = \''. $userid .'\' AND '.$timenow.' - lastaccess > 60');
1908 debugging('<p>Error: Could not insert a new entry to the Moodle log</p>'); // Don't throw an error
1910 if ($courseid != SITEID
&& !empty($courseid)) {
1911 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
;};
1913 if ($ulid = get_field('user_lastaccess', 'id', 'userid', $userid, 'courseid', $courseid)) {
1914 $res = $db->Execute("UPDATE {$CFG->prefix}user_lastaccess
1915 SET timeaccess=$timenow
1916 WHERE id = $ulid AND $timenow - timeaccess > 60");
1918 debugging('Error: Could not insert a new entry to the Moodle log'); // Don't throw an error
1921 $res = $db->Execute("INSERT INTO {$CFG->prefix}user_lastaccess
1922 ( userid, courseid, timeaccess)
1923 VALUES ($userid, $courseid, $timenow)");
1925 debugging('Error: Could not insert a new entry to the Moodle log'); // Don't throw an error
1928 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++
;};
1935 * Select all log records based on SQL criteria
1938 * @param string $select SQL select criteria
1939 * @param string $order SQL order by clause to sort the records returned
1940 * @param string $limitfrom ?
1941 * @param int $limitnum ?
1942 * @param int $totalcount Passed in by reference.
1944 * @todo Finish documenting this function
1946 function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1950 $order = 'ORDER BY '. $order;
1953 $selectsql = $CFG->prefix
.'log l LEFT JOIN '. $CFG->prefix
.'user u ON l.userid = u.id '. ((strlen($select) > 0) ?
'WHERE '. $select : '');
1954 $countsql = $CFG->prefix
.'log l '.((strlen($select) > 0) ?
' WHERE '. $select : '');
1956 $totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql");
1958 return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture
1959 FROM '. $selectsql .' '. $order, $limitfrom, $limitnum) ;
1964 * Select all log records for a given course and user
1968 * @param int $userid The id of the user as found in the 'user' table.
1969 * @param int $courseid The id of the course as found in the 'course' table.
1970 * @param string $coursestart ?
1971 * @todo Finish documenting this function
1973 function get_logs_usercourse($userid, $courseid, $coursestart) {
1977 $courseselect = ' AND course = \''. $courseid .'\' ';
1982 return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS
.") as day, count(*) as num
1983 FROM {$CFG->prefix}log
1984 WHERE userid = '$userid'
1985 AND time > '$coursestart' $courseselect
1990 * Select all log records for a given course, user, and day
1994 * @param int $userid The id of the user as found in the 'user' table.
1995 * @param int $courseid The id of the course as found in the 'course' table.
1996 * @param string $daystart ?
1998 * @todo Finish documenting this function
2000 function get_logs_userday($userid, $courseid, $daystart) {
2004 $courseselect = ' AND course = \''. $courseid .'\' ';
2009 return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS
.") as hour, count(*) as num
2010 FROM {$CFG->prefix}log
2011 WHERE userid = '$userid'
2012 AND time > '$daystart' $courseselect
2017 * Returns an object with counts of failed login attempts
2019 * Returns information about failed login attempts. If the current user is
2020 * an admin, then two numbers are returned: the number of attempts and the
2021 * number of accounts. For non-admins, only the attempts on the given user
2024 * @param string $mode Either 'admin', 'teacher' or 'everybody'
2025 * @param string $username The username we are searching for
2026 * @param string $lastlogin The date from which we are searching
2029 function count_login_failures($mode, $username, $lastlogin) {
2031 $select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin;
2033 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) { // Return information about all accounts
2034 if ($count->attempts
= count_records_select('log', $select)) {
2035 $count->accounts
= count_records_select('log', $select, 'COUNT(DISTINCT info)');
2038 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
2039 if ($count->attempts
= count_records_select('log', $select .' AND info = \''. $username .'\'')) {
2047 /// GENERAL HELPFUL THINGS ///////////////////////////////////
2050 * Dump a given object's information in a PRE block.
2052 * Mostly just used for debugging.
2054 * @param mixed $object The data to be printed
2056 function print_object($object) {
2057 echo '<pre class="notifytiny">' . htmlspecialchars(print_r($object,true)) . '</pre>';
2061 * Check whether a course is visible through its parents
2066 * - All we need from the course is ->category. _However_
2067 * if the course object has a categorypath property,
2068 * we'll save a dbquery
2070 * - If we return false, you'll still need to check if
2071 * the user can has the 'moodle/category:visibility'
2074 * - Will generate 2 DB calls.
2076 * - It does have a small local cache, however...
2078 * - Do NOT call this over many courses as it'll generate
2079 * DB traffic. Instead, see what get_my_courses() does.
2081 * @param mixed $object A course object
2084 function course_parent_visible($course = null) {
2089 if (!is_object($course)) {
2092 if (!empty($CFG->allowvisiblecoursesinhiddencategories
)) {
2096 if (!isset($mycache)) {
2099 // cast to force assoc array
2100 $k = (string)$course->category
;
2101 if (isset($mycache[$k])) {
2102 return $mycache[$k];
2106 if (isset($course->categorypath
)) {
2107 $path = $course->categorypath
;
2109 $path = get_field('course_categories', 'path',
2110 'id', $course->category
);
2112 $catids = substr($path,1); // strip leading slash
2113 $catids = str_replace('/',',',$catids);
2115 $sql = "SELECT MIN(visible)
2116 FROM {$CFG->prefix}course_categories
2117 WHERE id IN ($catids)";
2118 $vis = get_field_sql($sql);
2120 // cast to force assoc array
2121 $k = (string)$course->category
;
2122 $mycache[$k] = $vis;
2128 * This function is the official hook inside XMLDB stuff to delegate its debug to one
2129 * external function.
2131 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
2132 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
2134 * @param $message string contains the error message
2135 * @param $object object XMLDB object that fired the debug
2137 function xmldb_debug($message, $object) {
2139 debugging($message, DEBUG_DEVELOPER
);
2143 * true or false function to see if user can create any courses at all
2146 function user_can_create_courses() {
2148 // if user has course creation capability at any site or course cat, then return true;
2150 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM
, SITEID
))) {
2153 return (bool) count(get_creatable_categories());
2159 * get the list of categories the current user can create courses in
2162 function get_creatable_categories() {
2164 $creatablecats = array();
2165 if ($cats = get_records('course_categories')) {
2166 foreach ($cats as $cat) {
2167 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT
, $cat->id
))) {
2168 $creatablecats[$cat->id
] = $cat->name
;
2172 return $creatablecats;
2175 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: