MDL-11082 Improved groups upgrade performance 1.8x -> 1.9; thanks Eloy for telling...
[moodle-pu.git] / lib / datalib.php
blob0b2004c3c83aabb3ea3d79608cf2201bb7a601e6
1 <?php // $Id$
3 /**
4 * Library of functions for database manipulation.
6 * Other main libraries:
7 * - weblib.php - functions that produce web output
8 * - moodlelib.php - general-purpose Moodle functions
9 * @author Martin Dougiamas and many others
10 * @version $Id$
11 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
12 * @package moodlecore
16 /**
17 * Escape all dangerous characters in a data record
19 * $dataobject is an object containing needed data
20 * Run over each field exectuting addslashes() function
21 * to escape SQL unfriendly characters (e.g. quotes)
22 * Handy when writing back data read from the database
24 * @param $dataobject Object containing the database record
25 * @return object Same object with neccessary characters escaped
27 function addslashes_object( $dataobject ) {
28 $a = get_object_vars( $dataobject);
29 foreach ($a as $key=>$value) {
30 $a[$key] = addslashes( $value );
32 return (object)$a;
35 /// USER DATABASE ////////////////////////////////////////////////
37 /**
38 * Returns $user object of the main admin user
39 * primary admin = admin with lowest role_assignment id among admins
40 * @uses $CFG
41 * @return object(admin) An associative array representing the admin user.
43 function get_admin () {
45 global $CFG;
47 if ( $admins = get_admins() ) {
48 foreach ($admins as $admin) {
49 return $admin; // ie the first one
51 } else {
52 return false;
56 /**
57 * Returns list of all admins
59 * @uses $CFG
60 * @return object
62 function get_admins() {
64 global $CFG;
66 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
68 return get_users_by_capability($context, 'moodle/site:doanything', 'u.*, ra.id as adminid', 'ra.id ASC'); // only need first one
73 function get_courses_in_metacourse($metacourseid) {
74 global $CFG;
76 $sql = "SELECT c.id,c.shortname,c.fullname FROM {$CFG->prefix}course c, {$CFG->prefix}course_meta mc WHERE mc.parent_course = $metacourseid
77 AND mc.child_course = c.id ORDER BY c.shortname";
79 return get_records_sql($sql);
82 function get_courses_notin_metacourse($metacourseid,$count=false) {
84 global $CFG;
86 if ($count) {
87 $sql = "SELECT COUNT(c.id)";
88 } else {
89 $sql = "SELECT c.id,c.shortname,c.fullname";
92 $alreadycourses = get_courses_in_metacourse($metacourseid);
94 $sql .= " FROM {$CFG->prefix}course c WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
95 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1 ".((empty($count)) ? " ORDER BY c.shortname" : "");
97 return get_records_sql($sql);
100 function count_courses_notin_metacourse($metacourseid) {
101 global $CFG;
103 $alreadycourses = get_courses_in_metacourse($metacourseid);
105 $sql = "SELECT COUNT(c.id) AS notin FROM {$CFG->prefix}course c
106 WHERE ".((!empty($alreadycourses)) ? "c.id NOT IN (".implode(',',array_keys($alreadycourses)).")
107 AND " : "")." c.id !=$metacourseid and c.id != ".SITEID." and c.metacourse != 1";
109 if (!$count = get_record_sql($sql)) {
110 return 0;
113 return $count->notin;
117 * Search through course users
119 * If $coursid specifies the site course then this function searches
120 * through all undeleted and confirmed users
122 * @uses $CFG
123 * @uses SITEID
124 * @param int $courseid The course in question.
125 * @param int $groupid The group in question.
126 * @param string $searchtext ?
127 * @param string $sort ?
128 * @param string $exceptions ?
129 * @return object
131 function search_users($courseid, $groupid, $searchtext, $sort='', $exceptions='') {
132 global $CFG;
134 $LIKE = sql_ilike();
135 $fullname = sql_fullname('u.firstname', 'u.lastname');
137 if (!empty($exceptions)) {
138 $except = ' AND u.id NOT IN ('. $exceptions .') ';
139 } else {
140 $except = '';
143 if (!empty($sort)) {
144 $order = ' ORDER BY '. $sort;
145 } else {
146 $order = '';
149 $select = 'u.deleted = \'0\' AND u.confirmed = \'1\'';
151 if (!$courseid or $courseid == SITEID) {
152 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
153 FROM {$CFG->prefix}user u
154 WHERE $select
155 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
156 $except $order");
157 } else {
159 if ($groupid) {
160 //TODO:check. Remove group DB dependencies.
161 return get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
162 FROM {$CFG->prefix}user u,
163 {$CFG->prefix}groups_members gm
164 WHERE $select AND gm.groupid = '$groupid' AND gm.userid = u.id
165 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
166 $except $order");
167 } else {
168 $context = get_context_instance(CONTEXT_COURSE, $courseid);
169 $contextlists = get_related_contexts_string($context);
170 $users = get_records_sql("SELECT u.id, u.firstname, u.lastname, u.email
171 FROM {$CFG->prefix}user u,
172 {$CFG->prefix}role_assignments ra
173 WHERE $select AND ra.contextid $contextlists AND ra.userid = u.id
174 AND ($fullname $LIKE '%$searchtext%' OR u.email $LIKE '%$searchtext%')
175 $except $order");
177 return $users;
183 * Returns a list of all site users
184 * Obsolete, just calls get_course_users(SITEID)
186 * @uses SITEID
187 * @deprecated Use {@link get_course_users()} instead.
188 * @param string $fields A comma separated list of fields to be returned from the chosen table.
189 * @return object|false {@link $USER} records or false if error.
191 function get_site_users($sort='u.lastaccess DESC', $fields='*', $exceptions='') {
193 return get_course_users(SITEID, $sort, $exceptions, $fields);
198 * Returns a subset of users
200 * @uses $CFG
201 * @param bool $get If false then only a count of the records is returned
202 * @param string $search A simple string to search for
203 * @param bool $confirmed A switch to allow/disallow unconfirmed users
204 * @param array(int) $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
205 * @param string $sort A SQL snippet for the sorting criteria to use
206 * @param string $firstinitial ?
207 * @param string $lastinitial ?
208 * @param string $page ?
209 * @param string $recordsperpage ?
210 * @param string $fields A comma separated list of fields to be returned from the chosen table.
211 * @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.
213 function get_users($get=true, $search='', $confirmed=false, $exceptions='', $sort='firstname ASC',
214 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*') {
216 global $CFG;
218 if ($get && !$recordsperpage) {
219 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
220 'On large installations, this will probably cause an out of memory error. ' .
221 'Please think again and change your code so that it does not try to ' .
222 'load so much data into memory.', DEBUG_DEVELOPER);
225 $LIKE = sql_ilike();
226 $fullname = sql_fullname();
228 $select = 'username <> \'guest\' AND deleted = 0';
230 if (!empty($search)){
231 $search = trim($search);
232 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
235 if ($confirmed) {
236 $select .= ' AND confirmed = \'1\' ';
239 if ($exceptions) {
240 $select .= ' AND id NOT IN ('. $exceptions .') ';
243 if ($firstinitial) {
244 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\'';
246 if ($lastinitial) {
247 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\'';
250 if ($get) {
251 return get_records_select('user', $select, $sort, $fields, $page, $recordsperpage);
252 } else {
253 return count_records_select('user', $select);
259 * shortdesc (optional)
261 * longdesc
263 * @uses $CFG
264 * @param string $sort ?
265 * @param string $dir ?
266 * @param int $categoryid ?
267 * @param int $categoryid ?
268 * @param string $search ?
269 * @param string $firstinitial ?
270 * @param string $lastinitial ?
271 * @returnobject {@link $USER} records
272 * @todo Finish documenting this function
275 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
276 $search='', $firstinitial='', $lastinitial='', $remotewhere='') {
278 global $CFG;
280 $LIKE = sql_ilike();
281 $fullname = sql_fullname();
283 $select = "deleted <> '1'";
285 if (!empty($search)) {
286 $search = trim($search);
287 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%' OR username='$search') ";
290 if ($firstinitial) {
291 $select .= ' AND firstname '. $LIKE .' \''. $firstinitial .'%\' ';
294 if ($lastinitial) {
295 $select .= ' AND lastname '. $LIKE .' \''. $lastinitial .'%\' ';
298 $select .= $remotewhere;
300 if ($sort) {
301 $sort = ' ORDER BY '. $sort .' '. $dir;
304 /// warning: will return UNCONFIRMED USERS
305 return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
306 FROM {$CFG->prefix}user
307 WHERE $select $sort", $page, $recordsperpage);
313 * Full list of users that have confirmed their accounts.
315 * @uses $CFG
316 * @return object
318 function get_users_confirmed() {
319 global $CFG;
320 return get_records_sql("SELECT *
321 FROM {$CFG->prefix}user
322 WHERE confirmed = 1
323 AND deleted = 0
324 AND username <> 'guest'");
329 * Full list of users that have not yet confirmed their accounts.
331 * @uses $CFG
332 * @param string $cutofftime ?
333 * @return object {@link $USER} records
335 function get_users_unconfirmed($cutofftime=2000000000) {
336 global $CFG;
337 return get_records_sql("SELECT *
338 FROM {$CFG->prefix}user
339 WHERE confirmed = 0
340 AND firstaccess > 0
341 AND firstaccess < $cutofftime");
345 * All users that we have not seen for a really long time (ie dead accounts)
347 * @uses $CFG
348 * @param string $cutofftime ?
349 * @return object {@link $USER} records
351 function get_users_longtimenosee($cutofftime) {
352 global $CFG;
353 return get_records_sql("SELECT userid as id, courseid
354 FROM {$CFG->prefix}user_lastaccess
355 WHERE courseid != ".SITEID."
356 AND timeaccess > 0
357 AND timeaccess < $cutofftime ");
361 * Full list of bogus accounts that are probably not ever going to be used
363 * @uses $CFG
364 * @param string $cutofftime ?
365 * @return object {@link $USER} records
368 function get_users_not_fully_set_up($cutofftime=2000000000) {
369 global $CFG;
370 return get_records_sql("SELECT *
371 FROM {$CFG->prefix}user
372 WHERE confirmed = 1
373 AND lastaccess > 0
374 AND lastaccess < $cutofftime
375 AND deleted = 0
376 AND (lastname = '' OR firstname = '' OR email = '')");
379 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
383 * Returns $course object of the top-level site.
385 * @return course A {@link $COURSE} object for the site
387 function get_site() {
389 global $SITE;
391 if (!empty($SITE->id)) { // We already have a global to use, so return that
392 return $SITE;
395 if ($course = get_record('course', 'category', 0)) {
396 return $course;
397 } else {
398 return false;
403 * Returns list of courses, for whole site, or category
405 * Returns list of courses, for whole site, or category
406 * Important: Using c.* for fields is extremely expensive because
407 * we are using distinct. You almost _NEVER_ need all the fields
408 * in such a large SELECT
410 * @param type description
413 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
415 global $USER, $CFG;
417 if ($categoryid != "all" && is_numeric($categoryid)) {
418 $categoryselect = "WHERE c.category = '$categoryid'";
419 } else {
420 $categoryselect = "";
423 if (empty($sort)) {
424 $sortstatement = "";
425 } else {
426 $sortstatement = "ORDER BY $sort";
429 $visiblecourses = array();
431 // pull out all course matching the cat
432 if ($courses = get_records_sql("SELECT $fields
433 FROM {$CFG->prefix}course c
434 $categoryselect
435 $sortstatement")) {
437 // loop throught them
438 foreach ($courses as $course) {
440 if (isset($course->visible) && $course->visible <= 0) {
441 // for hidden courses, require visibility check
442 if (has_capability('moodle/course:viewhiddencourses',
443 get_context_instance(CONTEXT_COURSE, $course->id))) {
444 $visiblecourses [] = $course;
446 } else {
447 $visiblecourses [] = $course;
451 return $visiblecourses;
454 $teachertable = "";
455 $visiblecourses = "";
456 $sqland = "";
457 if (!empty($categoryselect)) {
458 $sqland = "AND ";
460 if (!empty($USER->id)) { // May need to check they are a teacher
461 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
462 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
463 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course = c.id";
465 } else {
466 $visiblecourses = "$sqland c.visible > 0";
469 if ($categoryselect or $visiblecourses) {
470 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
471 } else {
472 $selectsql = "{$CFG->prefix}course c $teachertable";
475 $extrafield = str_replace('ASC','',$sort);
476 $extrafield = str_replace('DESC','',$extrafield);
477 $extrafield = trim($extrafield);
478 if (!empty($extrafield)) {
479 $extrafield = ','.$extrafield;
481 return get_records_sql("SELECT ".((!empty($teachertable)) ? " DISTINCT " : "")." $fields $extrafield FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : ""));
487 * Returns list of courses, for whole site, or category
489 * Similar to get_courses, but allows paging
490 * Important: Using c.* for fields is extremely expensive because
491 * we are using distinct. You almost _NEVER_ need all the fields
492 * in such a large SELECT
494 * @param type description
497 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
498 &$totalcount, $limitfrom="", $limitnum="") {
500 global $USER, $CFG;
502 $categoryselect = "";
503 if ($categoryid != "all" && is_numeric($categoryid)) {
504 $categoryselect = "WHERE c.category = '$categoryid'";
505 } else {
506 $categoryselect = "";
509 // pull out all course matching the cat
510 $visiblecourses = array();
511 if (!($courses = get_records_sql("SELECT $fields
512 FROM {$CFG->prefix}course c
513 $categoryselect
514 ORDER BY $sort"))) {
515 return $visiblecourses;
517 $totalcount = 0;
519 if (!$limitnum) {
520 $limitnum = count($courses);
523 if (!$limitfrom) {
524 $limitfrom = 0;
527 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
528 foreach ($courses as $course) {
529 if ($course->visible <= 0) {
530 // for hidden courses, require visibility check
531 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
532 $totalcount++;
533 if ($totalcount > $limitfrom && count($visiblecourses) < $limitnum) {
534 $visiblecourses [] = $course;
537 } else {
538 $totalcount++;
539 if ($totalcount > $limitfrom && count($visiblecourses) < $limitnum) {
540 $visiblecourses [] = $course;
545 return $visiblecourses;
549 $categoryselect = "";
550 if ($categoryid != "all" && is_numeric($categoryid)) {
551 $categoryselect = "c.category = '$categoryid'";
554 $teachertable = "";
555 $visiblecourses = "";
556 $sqland = "";
557 if (!empty($categoryselect)) {
558 $sqland = "AND ";
560 if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
561 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
562 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
563 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
565 } else {
566 $visiblecourses = "$sqland c.visible > 0";
569 if ($limitfrom !== "") {
570 $limit = sql_paging_limit($limitfrom, $limitnum);
571 } else {
572 $limit = "";
575 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
577 $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
579 return get_records_sql("SELECT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
585 * List of courses that a user has access to view. Note that for admins,
586 * this usually includes every course on the system.
588 * @uses $CFG
589 * @param int $userid The user of interest
590 * @param string $sort the sortorder in the course table
591 * @param string $fields the fields to return
592 * @param bool $doanything True if using the doanything flag
593 * @param int $limit Maximum number of records to return, or 0 for unlimited
594 * @return array {@link $COURSE} of course objects
596 function get_my_courses($userid, $sort=NULL, $fields=NULL, $doanything=false,$limit=0) {
598 global $CFG, $USER;
600 // Default parameters
601 $d_sort = 'visible DESC,sortorder ASC';
602 $d_fields = 'id, category, sortorder, shortname, fullname, idnumber, newsitems, teacher, teachers, student, students, guest, startdate, visible, cost, enrol, summary, groupmode, groupmodeforce';
604 $usingdefaults = true;
605 if (is_null($sort) || $sort === $d_sort) {
606 $sort = $d_sort;
607 } else {
608 $usingdefaults = false;
610 if (is_null($fields) || $fields === $d_fields) {
611 $fields = $d_fields;
612 } else {
613 $usingdefaults = false;
616 $reallimit = 0; // this is only set if we are using a limit on the first call
618 // If using default params, we may have it cached...
619 if (!empty($USER->id) && ($USER->id == $userid) && $usingdefaults) {
620 if (!empty($USER->mycourses[$doanything])) {
621 if ($limit && $limit < count($USER->mycourses[$doanything])) {
622 //silence warnings in PHP 4.x - the last param was added in PHP 5.0.2
623 return @array_slice($USER->mycourses[$doanything], 0, $limit, true);
624 } else {
625 return $USER->mycourses[$doanything];
627 } else {
628 // now, this is the first call, i.e. no cache, and we are using defaults, with a limit supplied,
629 // we need to store the limit somewhere, retrieve all, cache properly and then slice the array
630 // to return the proper number of entries. This is so that we don't keep missing calls like limit 20,20,20
631 if ($limit) {
632 $reallimit = $limit;
633 $limit = 0;
638 $mycourses = array();
640 // Fix fields to refer to the course table c
641 $fields=preg_replace('/([a-z0-9*]+)/','c.$1',$fields);
643 // Attempt to filter the list of courses in order to reduce the number
644 // of queries in the next part.
646 // Check root permissions
647 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
649 // Guest's do not have any courses
650 if (has_capability('moodle/legacy:guest',$sitecontext,$userid,false)) {
651 return(array());
654 // we can optimise some things for true admins
655 $candoanything = false;
656 if ($doanything && has_capability('moodle/site:doanything',$sitecontext,$userid,true)) {
657 $candoanything = true;
660 if ($candoanything || has_capability('moodle/course:view',$sitecontext,$userid,$doanything)) {
661 // User can view all courses, although there might be exceptions
662 // which we will filter later.
663 $rs = get_recordset('course c', '', '', $sort, $fields);
664 } else {
665 // The only other context level above courses that applies to moodle/course:view
666 // is category. So we consider:
667 // 1. All courses in which the user is assigned a role
668 // 2. All courses in categories in which the user is assigned a role
669 // 2BIS. All courses in subcategories in which the user gets assignment because he is assigned in one of its ascendant categories
670 // 3. All courses which have overrides for moodle/course:view
671 // Remember that this is just a filter. We check each individual course later.
672 // However for a typical student on a large system this can reduce the
673 // number of courses considered from around 2,000 to around 2, with corresponding
674 // reduction in the number of queries needed.
675 $rs=get_recordset_sql("
676 SELECT $fields
677 FROM {$CFG->prefix}course c, (
678 SELECT
679 c.id
680 FROM
681 {$CFG->prefix}role_assignments ra
682 INNER JOIN {$CFG->prefix}context x ON x.id = ra.contextid
683 INNER JOIN {$CFG->prefix}course c ON x.instanceid = c.id
684 WHERE
685 ra.userid = $userid AND
686 x.contextlevel = 50
687 UNION
688 SELECT
689 c.id
690 FROM
691 {$CFG->prefix}role_assignments ra
692 INNER JOIN {$CFG->prefix}context x ON x.id = ra.contextid
693 INNER JOIN {$CFG->prefix}course_categories a ON a.path LIKE ".sql_concat("'%/'", 'x.instanceid', "'/%'")." OR x.instanceid = a.id
694 INNER JOIN {$CFG->prefix}course c ON c.category = a.id
695 WHERE
696 ra.userid = $userid AND
697 x.contextlevel = 40
698 UNION
699 SELECT
700 c.id
701 FROM
702 {$CFG->prefix}role_capabilities ca
703 INNER JOIN {$CFG->prefix}context x ON x.id = ca.contextid
704 INNER JOIN {$CFG->prefix}course c ON c.id = x.instanceid
705 WHERE
706 ca.capability = 'moodle/course:view' AND
707 ca.contextid != {$sitecontext->id} AND
708 x.contextlevel = 50
709 ) cids
710 WHERE c.id = cids.id
711 ORDER BY $sort"
715 if ($rs && $rs->RecordCount() > 0) {
716 while ($course = rs_fetch_next_record($rs)) {
717 if ($course->id != SITEID) {
719 if ($candoanything) { // no need for further checks...
720 $mycourses[$course->id] = $course;
721 continue;
724 // users with moodle/course:view are considered course participants
725 // the course needs to be visible, or user must have moodle/course:viewhiddencourses
726 // capability set to view hidden courses
727 $context = get_context_instance(CONTEXT_COURSE, $course->id);
728 if ( has_capability('moodle/course:view', $context, $userid, $doanything) &&
729 !has_capability('moodle/legacy:guest', $context, $userid, false) &&
730 ($course->visible || has_capability('moodle/course:viewhiddencourses', $context, $userid))) {
731 $mycourses[$course->id] = $course;
733 // Only return a limited number of courses if limit is set
734 if($limit>0) {
735 $limit--;
736 if($limit==0) {
737 break;
745 // Cache if using default params...
746 if (!empty($USER->id) && ($USER->id == $userid) && $usingdefaults && $limit == 0) {
747 $USER->mycourses[$doanything] = $mycourses;
750 if (!empty($mycourses) && $reallimit) {
751 return array_slice($mycourses, 0, $reallimit, true);
752 } else {
753 return $mycourses;
759 * A list of courses that match a search
761 * @uses $CFG
762 * @param array $searchterms ?
763 * @param string $sort ?
764 * @param int $page ?
765 * @param int $recordsperpage ?
766 * @param int $totalcount Passed in by reference. ?
767 * @return object {@link $COURSE} records
769 function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
771 global $CFG;
773 //to allow case-insensitive search for postgesql
774 if ($CFG->dbfamily == 'postgres') {
775 $LIKE = 'ILIKE';
776 $NOTLIKE = 'NOT ILIKE'; // case-insensitive
777 $REGEXP = '~*';
778 $NOTREGEXP = '!~*';
779 } else {
780 $LIKE = 'LIKE';
781 $NOTLIKE = 'NOT LIKE';
782 $REGEXP = 'REGEXP';
783 $NOTREGEXP = 'NOT REGEXP';
786 $fullnamesearch = '';
787 $summarysearch = '';
789 foreach ($searchterms as $searchterm) {
791 /// Under Oracle and MSSQL, trim the + and - operators and perform
792 /// simpler LIKE search
793 if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
794 $searchterm = trim($searchterm, '+-');
797 if ($fullnamesearch) {
798 $fullnamesearch .= ' AND ';
800 if ($summarysearch) {
801 $summarysearch .= ' AND ';
804 if (substr($searchterm,0,1) == '+') {
805 $searchterm = substr($searchterm,1);
806 $summarysearch .= " summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
807 $fullnamesearch .= " fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
808 } else if (substr($searchterm,0,1) == "-") {
809 $searchterm = substr($searchterm,1);
810 $summarysearch .= " summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
811 $fullnamesearch .= " fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
812 } else {
813 $summarysearch .= ' summary '. $LIKE .' \'%'. $searchterm .'%\' ';
814 $fullnamesearch .= ' fullname '. $LIKE .' \'%'. $searchterm .'%\' ';
819 $selectsql = $CFG->prefix .'course WHERE ('. $fullnamesearch .' OR '. $summarysearch .') AND category > \'0\'';
821 $totalcount = count_records_sql('SELECT COUNT(*) FROM '. $selectsql);
823 $courses = get_records_sql('SELECT * FROM '. $selectsql .' ORDER BY '. $sort, $page, $recordsperpage);
825 if ($courses) { /// Remove unavailable courses from the list
826 foreach ($courses as $key => $course) {
827 if (!$course->visible) {
828 if (!has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
829 unset($courses[$key]);
830 $totalcount--;
836 return $courses;
841 * Returns a sorted list of categories
843 * @param string $parent The parent category if any
844 * @param string $sort the sortorder
845 * @return array of categories
847 function get_categories($parent='none', $sort='sortorder ASC') {
849 if ($parent === 'none') {
850 $categories = get_records('course_categories', '', '', $sort);
851 } else {
852 $categories = get_records('course_categories', 'parent', $parent, $sort);
854 if ($categories) { /// Remove unavailable categories from the list
855 foreach ($categories as $key => $category) {
856 if (!$category->visible) {
857 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $category->id))) {
858 unset($categories[$key]);
863 return $categories;
868 * Returns an array of category ids of all the subcategories for a given
869 * category.
870 * @param $catid - The id of the category whose subcategories we want to find.
871 * @return array of category ids.
873 function get_all_subcategories($catid) {
875 $subcats = array();
877 if ($categories = get_records('course_categories', 'parent', $catid)) {
878 foreach ($categories as $cat) {
879 array_push($subcats, $cat->id);
880 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
883 return $subcats;
888 * This recursive function makes sure that the courseorder is consecutive
890 * @param type description
892 * $n is the starting point, offered only for compatilibity -- will be ignored!
893 * $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
894 * safely from 1.4 to 1.5
896 function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
898 global $CFG;
900 $count = 0;
902 $catgap = 1000; // "standard" category gap
903 $tolerance = 200; // how "close" categories can get
905 if ($categoryid > 0){
906 // update depth and path
907 $cat = get_record('course_categories', 'id', $categoryid);
908 if ($cat->parent == 0) {
909 $depth = 0;
910 $path = '';
911 } else if ($depth == 0 ) { // doesn't make sense; get from DB
912 // this is only called if the $depth parameter looks dodgy
913 $parent = get_record('course_categories', 'id', $cat->parent);
914 $path = $parent->path;
915 $depth = $parent->depth;
917 $path = $path . '/' . $categoryid;
918 $depth = $depth + 1;
920 set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
921 set_field('course_categories', 'depth', $depth, 'id', $categoryid);
924 // get some basic info about courses in the category
925 $info = get_record_sql('SELECT MIN(sortorder) AS min,
926 MAX(sortorder) AS max,
927 COUNT(sortorder) AS count
928 FROM ' . $CFG->prefix . 'course
929 WHERE category=' . $categoryid);
930 if (is_object($info)) { // no courses?
931 $max = $info->max;
932 $count = $info->count;
933 $min = $info->min;
934 unset($info);
937 if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
938 $n = $min;
941 // $hasgap flag indicates whether there's a gap in the sequence
942 $hasgap = false;
943 if ($max-$min+1 != $count) {
944 $hasgap = true;
947 // $mustshift indicates whether the sequence must be shifted to
948 // meet its range
949 $mustshift = false;
950 if ($min < $n+$tolerance || $min > $n+$tolerance+$catgap ) {
951 $mustshift = true;
954 // actually sort only if there are courses,
955 // and we meet one ofthe triggers:
956 // - safe flag
957 // - they are not in a continuos block
958 // - they are too close to the 'bottom'
959 if ($count && ( $safe || $hasgap || $mustshift ) ) {
960 // special, optimized case where all we need is to shift
961 if ( $mustshift && !$safe && !$hasgap) {
962 $shift = $n + $catgap - $min;
963 // UPDATE course SET sortorder=sortorder+$shift
964 execute_sql("UPDATE {$CFG->prefix}course
965 SET sortorder=sortorder+$shift
966 WHERE category=$categoryid", 0);
967 $n = $n + $catgap + $count;
969 } else { // do it slowly
970 $n = $n + $catgap;
971 // if the new sequence overlaps the current sequence, lack of transactions
972 // will stop us -- shift things aside for a moment...
973 if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbfamily==='mysql')) {
974 $shift = $max + $n + 1000;
975 execute_sql("UPDATE {$CFG->prefix}course
976 SET sortorder=sortorder+$shift
977 WHERE category=$categoryid", 0);
980 $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
981 begin_sql();
982 foreach ($courses as $course) {
983 if ($course->sortorder != $n ) { // save db traffic
984 set_field('course', 'sortorder', $n, 'id', $course->id);
986 $n++;
988 commit_sql();
991 set_field('course_categories', 'coursecount', $count, 'id', $categoryid);
993 // $n could need updating
994 $max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid");
995 if ($max > $n) {
996 $n = $max;
999 if ($categories = get_categories($categoryid)) {
1000 foreach ($categories as $category) {
1001 $n = fix_course_sortorder($category->id, $n, $safe, $depth, $path);
1005 return $n+1;
1009 * List of remote courses that a user has access to via MNET.
1010 * Works only on the IDP
1012 * @uses $CFG, $USER
1013 * @return array {@link $COURSE} of course objects
1015 function get_my_remotecourses($userid=0) {
1016 global $CFG, $USER;
1018 if (empty($userid)) {
1019 $userid = $USER->id;
1022 $sql = "SELECT c.remoteid, c.shortname, c.fullname,
1023 c.hostid, c.summary, c.cat_name,
1024 h.name AS hostname
1025 FROM {$CFG->prefix}mnet_enrol_course c
1026 JOIN {$CFG->prefix}mnet_enrol_assignments a ON c.id=a.courseid
1027 JOIN {$CFG->prefix}mnet_host h ON c.hostid=h.id
1028 WHERE a.userid={$userid}";
1030 return get_records_sql($sql);
1034 * List of remote hosts that a user has access to via MNET.
1035 * Works on the SP
1037 * @uses $CFG, $USER
1038 * @return array of host objects
1040 function get_my_remotehosts() {
1041 global $CFG, $USER;
1043 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1044 return false; // Return nothing on the IDP
1046 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1047 return $USER->mnet_foreign_host_array;
1049 return false;
1053 * This function creates a default separated/connected scale
1055 * This function creates a default separated/connected scale
1056 * so there's something in the database. The locations of
1057 * strings and files is a bit odd, but this is because we
1058 * need to maintain backward compatibility with many different
1059 * existing language translations and older sites.
1061 * @uses $CFG
1063 function make_default_scale() {
1065 global $CFG;
1067 $defaultscale = NULL;
1068 $defaultscale->courseid = 0;
1069 $defaultscale->userid = 0;
1070 $defaultscale->name = get_string('separateandconnected');
1071 $defaultscale->scale = get_string('postrating1', 'forum').','.
1072 get_string('postrating2', 'forum').','.
1073 get_string('postrating3', 'forum');
1074 $defaultscale->timemodified = time();
1076 /// Read in the big description from the file. Note this is not
1077 /// HTML (despite the file extension) but Moodle format text.
1078 $parentlang = get_string('parentlang');
1079 if (is_readable($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1080 $file = file($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1081 } else if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1082 $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1083 } else if ($parentlang and is_readable($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1084 $file = file($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
1085 } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1086 $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
1087 } else if (is_readable($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html')) {
1088 $file = file($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html');
1089 } else {
1090 $file = '';
1093 $defaultscale->description = addslashes(implode('', $file));
1095 if ($defaultscale->id = insert_record('scale', $defaultscale)) {
1096 execute_sql('UPDATE '. $CFG->prefix .'forum SET scale = \''. $defaultscale->id .'\'', false);
1102 * Returns a menu of all available scales from the site as well as the given course
1104 * @uses $CFG
1105 * @param int $courseid The id of the course as found in the 'course' table.
1106 * @return object
1108 function get_scales_menu($courseid=0) {
1110 global $CFG;
1112 $sql = "SELECT id, name FROM {$CFG->prefix}scale
1113 WHERE courseid = '0' or courseid = '$courseid'
1114 ORDER BY courseid ASC, name ASC";
1116 if ($scales = get_records_sql_menu($sql)) {
1117 return $scales;
1120 make_default_scale();
1122 return get_records_sql_menu($sql);
1128 * Given a set of timezone records, put them in the database, replacing what is there
1130 * @uses $CFG
1131 * @param array $timezones An array of timezone records
1133 function update_timezone_records($timezones) {
1134 /// Given a set of timezone records, put them in the database
1136 global $CFG;
1138 /// Clear out all the old stuff
1139 execute_sql('TRUNCATE TABLE '.$CFG->prefix.'timezone', false);
1141 /// Insert all the new stuff
1142 foreach ($timezones as $timezone) {
1143 insert_record('timezone', $timezone);
1148 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1151 * Just gets a raw list of all modules in a course
1153 * @uses $CFG
1154 * @param int $courseid The id of the course as found in the 'course' table.
1155 * @return object
1157 function get_course_mods($courseid) {
1158 global $CFG;
1160 if (empty($courseid)) {
1161 return false; // avoid warnings
1164 return get_records_sql("SELECT cm.*, m.name as modname
1165 FROM {$CFG->prefix}modules m,
1166 {$CFG->prefix}course_modules cm
1167 WHERE cm.course = '$courseid'
1168 AND cm.module = m.id ");
1173 * Given an id of a course module, finds the coursemodule description
1175 * @param string $modulename name of module type, eg. resource, assignment,...
1176 * @param int $cmid course module id (id in course_modules table)
1177 * @param int $courseid optional course id for extra validation
1178 * @return object course module instance with instance and module name
1180 function get_coursemodule_from_id($modulename, $cmid, $courseid=0) {
1182 global $CFG;
1184 $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
1186 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1187 FROM {$CFG->prefix}course_modules cm,
1188 {$CFG->prefix}modules md,
1189 {$CFG->prefix}$modulename m
1190 WHERE $courseselect
1191 cm.id = '$cmid' AND
1192 cm.instance = m.id AND
1193 md.name = '$modulename' AND
1194 md.id = cm.module");
1198 * Given an instance number of a module, finds the coursemodule description
1200 * @param string $modulename name of module type, eg. resource, assignment,...
1201 * @param int $instance module instance number (id in resource, assignment etc. table)
1202 * @param int $courseid optional course id for extra validation
1203 * @return object course module instance with instance and module name
1205 function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
1207 global $CFG;
1209 $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
1211 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1212 FROM {$CFG->prefix}course_modules cm,
1213 {$CFG->prefix}modules md,
1214 {$CFG->prefix}$modulename m
1215 WHERE $courseselect
1216 cm.instance = m.id AND
1217 md.name = '$modulename' AND
1218 md.id = cm.module AND
1219 m.id = '$instance'");
1224 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1226 * Returns an array of all the active instances of a particular
1227 * module in given courses, sorted in the order they are defined
1228 * in the course. Returns false on any errors.
1230 * @uses $CFG
1231 * @param string $modulename The name of the module to get instances for
1232 * @param array $courses This depends on an accurate $course->modinfo
1233 * @return array of instances
1235 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1236 global $CFG;
1237 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1238 return array();
1240 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode, cm.course
1241 FROM {$CFG->prefix}course_modules cm,
1242 {$CFG->prefix}course_sections cw,
1243 {$CFG->prefix}modules md,
1244 {$CFG->prefix}$modulename m
1245 WHERE cm.course IN (".implode(',',array_keys($courses)).") AND
1246 cm.instance = m.id AND
1247 cm.section = cw.id AND
1248 md.name = '$modulename' AND
1249 md.id = cm.module")) {
1250 return array();
1253 $outputarray = array();
1255 foreach ($courses as $course) {
1256 if ($includeinvisible) {
1257 $invisible = -1;
1258 } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id), $userid)) {
1259 // Usually hide non-visible instances from students
1260 $invisible = -1;
1261 } else {
1262 $invisible = 0;
1265 /// Casting $course->modinfo to string prevents one notice when the field is null
1266 if (!$modinfo = unserialize((string)$course->modinfo)) {
1267 continue;
1269 foreach ($modinfo as $mod) {
1270 if ($mod->mod == $modulename and $mod->visible > $invisible) {
1271 $instance = $rawmods[$mod->cm];
1272 if (!empty($mod->extra)) {
1273 $instance->extra = $mod->extra;
1275 $outputarray[] = $instance;
1280 return $outputarray;
1285 * Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined
1287 * Returns an array of all the active instances of a particular
1288 * module in a given course, sorted in the order they are defined
1289 * in the course. Returns false on any errors.
1291 * @uses $CFG
1292 * @param string $modulename The name of the module to get instances for
1293 * @param object(course) $course This depends on an accurate $course->modinfo
1295 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1297 global $CFG;
1299 if (empty($course->modinfo)) {
1300 return array();
1303 if (!$modinfo = unserialize((string)$course->modinfo)) {
1304 return array();
1307 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode,cm.groupingid
1308 FROM {$CFG->prefix}course_modules cm,
1309 {$CFG->prefix}course_sections cw,
1310 {$CFG->prefix}modules md,
1311 {$CFG->prefix}$modulename m
1312 WHERE cm.course = '$course->id' AND
1313 cm.instance = m.id AND
1314 cm.section = cw.id AND
1315 md.name = '$modulename' AND
1316 md.id = cm.module")) {
1317 return array();
1320 if ($includeinvisible) {
1321 $invisible = -1;
1322 } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id), $userid)) {
1323 // Usually hide non-visible instances from students
1324 $invisible = -1;
1325 } else {
1326 $invisible = 0;
1329 $outputarray = array();
1331 foreach ($modinfo as $mod) {
1332 $mod->id = $mod->cm;
1333 $mod->course = $course->id;
1334 if (!groups_course_module_visible($mod)) {
1335 continue;
1337 if ($mod->mod == $modulename and $mod->visible > $invisible) {
1338 $instance = $rawmods[$mod->cm];
1339 if (!empty($mod->extra)) {
1340 $instance->extra = $mod->extra;
1342 $outputarray[] = $instance;
1346 return $outputarray;
1352 * Determine whether a module instance is visible within a course
1354 * Given a valid module object with info about the id and course,
1355 * and the module's type (eg "forum") returns whether the object
1356 * is visible or not
1358 * @uses $CFG
1359 * @param $moduletype Name of the module eg 'forum'
1360 * @param $module Object which is the instance of the module
1361 * @return bool
1363 function instance_is_visible($moduletype, $module) {
1365 global $CFG;
1367 if (!empty($module->id)) {
1368 if ($records = get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1369 FROM {$CFG->prefix}course_modules cm,
1370 {$CFG->prefix}modules m
1371 WHERE cm.course = '$module->course' AND
1372 cm.module = m.id AND
1373 m.name = '$moduletype' AND
1374 cm.instance = '$module->id'")) {
1376 foreach ($records as $record) { // there should only be one - use the first one
1377 return $record->visible && groups_course_module_visible($record);
1381 return true; // visible by default!
1387 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1391 * Add an entry to the log table.
1393 * Add an entry to the log table. These are "action" focussed rather
1394 * than web server hits, and provide a way to easily reconstruct what
1395 * any particular student has been doing.
1397 * @uses $CFG
1398 * @uses $USER
1399 * @uses $db
1400 * @uses $REMOTE_ADDR
1401 * @uses SITEID
1402 * @param int $courseid The course id
1403 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
1404 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1405 * @param string $url The file and parameters used to see the results of the action
1406 * @param string $info Additional description information
1407 * @param string $cm The course_module->id if there is one
1408 * @param string $user If log regards $user other than $USER
1410 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1411 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1412 // This is for a good reason: it is the most frequently used DB update function,
1413 // so it has been optimised for speed.
1414 global $db, $CFG, $USER;
1416 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
1417 $cm = 0;
1420 if ($user) {
1421 $userid = $user;
1422 } else {
1423 if (!empty($USER->realuser)) { // Don't log
1424 return;
1426 $userid = empty($USER->id) ? '0' : $USER->id;
1429 $REMOTE_ADDR = getremoteaddr();
1431 $timenow = time();
1432 $info = addslashes($info);
1433 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1434 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
1437 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; $PERF->logwrites++;};
1439 if ($CFG->type = 'oci8po') {
1440 if (empty($info)) {
1441 $info = ' ';
1445 $result = $db->Execute('INSERT INTO '. $CFG->prefix .'log (time, userid, course, ip, module, cmid, action, url, info)
1446 VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')");
1448 if (!$result and debugging()) {
1449 echo '<p>Error: Could not insert a new entry to the Moodle log</p>'; // Don't throw an error
1452 /// Store lastaccess times for the current user, do not use in cron and other commandline scripts
1454 if (!empty($USER->id) && ($userid == $USER->id) && !defined('FULLME')) {
1455 $db->Execute('UPDATE '. $CFG->prefix .'user
1456 SET lastip=\''. $REMOTE_ADDR .'\', lastaccess=\''. $timenow .'\'
1457 WHERE id = \''. $userid .'\' ');
1458 if ($courseid != SITEID && !empty($courseid)) {
1459 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
1461 if ($record = get_record('user_lastaccess', 'userid', $userid, 'courseid', $courseid)) {
1462 $record->timeaccess = $timenow;
1463 return update_record('user_lastaccess', $record);
1464 } else {
1465 $record = new object;
1466 $record->userid = $userid;
1467 $record->courseid = $courseid;
1468 $record->timeaccess = $timenow;
1469 return insert_record('user_lastaccess', $record);
1477 * Select all log records based on SQL criteria
1479 * @uses $CFG
1480 * @param string $select SQL select criteria
1481 * @param string $order SQL order by clause to sort the records returned
1482 * @param string $limitfrom ?
1483 * @param int $limitnum ?
1484 * @param int $totalcount Passed in by reference.
1485 * @return object
1486 * @todo Finish documenting this function
1488 function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1489 global $CFG;
1491 if ($order) {
1492 $order = 'ORDER BY '. $order;
1495 $selectsql = $CFG->prefix .'log l LEFT JOIN '. $CFG->prefix .'user u ON l.userid = u.id '. ((strlen($select) > 0) ? 'WHERE '. $select : '');
1496 $countsql = $CFG->prefix.'log l '.((strlen($select) > 0) ? ' WHERE '. $select : '');
1498 $totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql");
1500 return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture
1501 FROM '. $selectsql .' '. $order, $limitfrom, $limitnum) ;
1506 * Select all log records for a given course and user
1508 * @uses $CFG
1509 * @uses DAYSECS
1510 * @param int $userid The id of the user as found in the 'user' table.
1511 * @param int $courseid The id of the course as found in the 'course' table.
1512 * @param string $coursestart ?
1513 * @todo Finish documenting this function
1515 function get_logs_usercourse($userid, $courseid, $coursestart) {
1516 global $CFG;
1518 if ($courseid) {
1519 $courseselect = ' AND course = \''. $courseid .'\' ';
1520 } else {
1521 $courseselect = '';
1524 return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS .") as day, count(*) as num
1525 FROM {$CFG->prefix}log
1526 WHERE userid = '$userid'
1527 AND time > '$coursestart' $courseselect
1528 GROUP BY day ");
1532 * Select all log records for a given course, user, and day
1534 * @uses $CFG
1535 * @uses HOURSECS
1536 * @param int $userid The id of the user as found in the 'user' table.
1537 * @param int $courseid The id of the course as found in the 'course' table.
1538 * @param string $daystart ?
1539 * @return object
1540 * @todo Finish documenting this function
1542 function get_logs_userday($userid, $courseid, $daystart) {
1543 global $CFG;
1545 if ($courseid) {
1546 $courseselect = ' AND course = \''. $courseid .'\' ';
1547 } else {
1548 $courseselect = '';
1551 return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS .") as hour, count(*) as num
1552 FROM {$CFG->prefix}log
1553 WHERE userid = '$userid'
1554 AND time > '$daystart' $courseselect
1555 GROUP BY hour ");
1559 * Returns an object with counts of failed login attempts
1561 * Returns information about failed login attempts. If the current user is
1562 * an admin, then two numbers are returned: the number of attempts and the
1563 * number of accounts. For non-admins, only the attempts on the given user
1564 * are shown.
1566 * @param string $mode Either 'admin', 'teacher' or 'everybody'
1567 * @param string $username The username we are searching for
1568 * @param string $lastlogin The date from which we are searching
1569 * @return int
1571 function count_login_failures($mode, $username, $lastlogin) {
1573 $select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin;
1575 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM, SITEID))) { // Return information about all accounts
1576 if ($count->attempts = count_records_select('log', $select)) {
1577 $count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)');
1578 return $count;
1580 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
1581 if ($count->attempts = count_records_select('log', $select .' AND info = \''. $username .'\'')) {
1582 return $count;
1585 return NULL;
1589 /// GENERAL HELPFUL THINGS ///////////////////////////////////
1592 * Dump a given object's information in a PRE block.
1594 * Mostly just used for debugging.
1596 * @param mixed $object The data to be printed
1598 function print_object($object) {
1599 echo '<pre class="notifytiny">' . htmlspecialchars(print_r($object,true)) . '</pre>';
1602 function course_parent_visible($course = null) {
1603 global $CFG;
1605 if (empty($course)) {
1606 return true;
1608 if (!empty($CFG->allowvisiblecoursesinhiddencategories)) {
1609 return true;
1611 return category_parent_visible($course->category);
1614 function category_parent_visible($parent = 0) {
1616 static $visible;
1618 if (!$parent) {
1619 return true;
1622 if (empty($visible)) {
1623 $visible = array(); // initialize
1626 if (array_key_exists($parent,$visible)) {
1627 return $visible[$parent];
1630 $category = get_record('course_categories', 'id', $parent);
1631 $list = explode('/', preg_replace('/^\/(.*)$/', '$1', $category->path));
1632 $list[] = $parent;
1633 $parents = get_records_list('course_categories', 'id', implode(',', $list), 'depth DESC');
1634 $v = true;
1635 foreach ($parents as $p) {
1636 if (!$p->visible) {
1637 $v = false;
1640 $visible[$parent] = $v; // now cache it
1641 return $v;
1645 * This function is the official hook inside XMLDB stuff to delegate its debug to one
1646 * external function.
1648 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1649 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1651 * @param $message string contains the error message
1652 * @param $object object XMLDB object that fired the debug
1654 function xmldb_debug($message, $object) {
1656 debugging($message, DEBUG_DEVELOPER);
1660 * Get the lists of courses the current user has $cap capability in
1661 * I am not sure if this is needed, it loops through all courses so
1662 * could cause performance problems.
1663 * If it's not used, we can use a faster function to detect
1664 * capability in restorelib.php
1665 * @param string $cap
1666 * @return array
1668 function get_capability_courses($cap) {
1669 global $USER;
1671 $mycourses = array();
1672 if ($courses = get_records('course')) {
1673 foreach ($courses as $course) {
1674 if (has_capability($cap, get_context_instance(CONTEXT_COURSE, $course->id))) {
1675 $mycourses[] = $course->id;
1680 return $mycourses;
1684 * true or false function to see if user can create any courses at all
1685 * @return bool
1687 function user_can_create_courses() {
1688 global $USER;
1689 // if user has course creation capability at any site or course cat, then return true;
1691 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1692 return true;
1693 } else {
1694 return (bool) count(get_creatable_categories());
1700 * get the list of categories the current user can create courses in
1701 * @return array
1703 function get_creatable_categories() {
1705 $creatablecats = array();
1706 if ($cats = get_records('course_categories')) {
1707 foreach ($cats as $cat) {
1708 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) {
1709 $creatablecats[$cat->id] = $cat->name;
1713 return $creatablecats;
1716 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: