Merge branch 'MDL-32780-CLEAN' of git://github.com/netspotau/moodle-mod_assign
[moodle.git] / lib / datalib.php
blob99f6b913be2c08fd19c70bccff2d2eb0012a817f
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Library of functions for database manipulation.
20 * Other main libraries:
21 * - weblib.php - functions that produce web output
22 * - moodlelib.php - general-purpose Moodle functions
24 * @package core
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * The maximum courses in a category
33 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
35 define('MAX_COURSES_IN_CATEGORY', 10000);
37 /**
38 * The maximum number of course categories
39 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
41 define('MAX_COURSE_CATEGORIES', 10000);
43 /**
44 * Number of seconds to wait before updating lastaccess information in DB.
46 define('LASTACCESS_UPDATE_SECS', 60);
48 /**
49 * Returns $user object of the main admin user
51 * @static stdClass $mainadmin
52 * @return stdClass {@link $USER} record from DB, false if not found
54 function get_admin() {
55 global $CFG, $DB;
57 static $mainadmin = null;
59 if (isset($mainadmin)) {
60 return clone($mainadmin);
63 if (empty($CFG->siteadmins)) { // Should not happen on an ordinary site
64 return false;
67 foreach (explode(',', $CFG->siteadmins) as $id) {
68 if ($user = $DB->get_record('user', array('id'=>$id, 'deleted'=>0))) {
69 $mainadmin = $user;
70 break;
74 if ($mainadmin) {
75 return clone($mainadmin);
76 } else {
77 // this should not happen
78 return false;
82 /**
83 * Returns list of all admins, using 1 DB query
85 * @return array
87 function get_admins() {
88 global $DB, $CFG;
90 if (empty($CFG->siteadmins)) { // Should not happen on an ordinary site
91 return array();
94 $sql = "SELECT u.*
95 FROM {user} u
96 WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
98 return $DB->get_records_sql($sql);
102 * Search through course users
104 * If $coursid specifies the site course then this function searches
105 * through all undeleted and confirmed users
107 * @global object
108 * @uses SITEID
109 * @uses SQL_PARAMS_NAMED
110 * @uses CONTEXT_COURSE
111 * @param int $courseid The course in question.
112 * @param int $groupid The group in question.
113 * @param string $searchtext The string to search for
114 * @param string $sort A field to sort by
115 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
116 * @return array
118 function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
119 global $DB;
121 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
123 if (!empty($exceptions)) {
124 list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
125 $except = "AND u.id $exceptions";
126 } else {
127 $except = "";
128 $params = array();
131 if (!empty($sort)) {
132 $order = "ORDER BY $sort";
133 } else {
134 $order = "";
137 $select = "u.deleted = 0 AND u.confirmed = 1 AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
138 $params['search1'] = "%$searchtext%";
139 $params['search2'] = "%$searchtext%";
141 if (!$courseid or $courseid == SITEID) {
142 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
143 FROM {user} u
144 WHERE $select
145 $except
146 $order";
147 return $DB->get_records_sql($sql, $params);
149 } else {
150 if ($groupid) {
151 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
152 FROM {user} u
153 JOIN {groups_members} gm ON gm.userid = u.id
154 WHERE $select AND gm.groupid = :groupid
155 $except
156 $order";
157 $params['groupid'] = $groupid;
158 return $DB->get_records_sql($sql, $params);
160 } else {
161 $context = get_context_instance(CONTEXT_COURSE, $courseid);
162 $contextlists = get_related_contexts_string($context);
164 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
165 FROM {user} u
166 JOIN {role_assignments} ra ON ra.userid = u.id
167 WHERE $select AND ra.contextid $contextlists
168 $except
169 $order";
170 return $DB->get_records_sql($sql, $params);
176 * Returns a subset of users
178 * @global object
179 * @uses DEBUG_DEVELOPER
180 * @uses SQL_PARAMS_NAMED
181 * @param bool $get If false then only a count of the records is returned
182 * @param string $search A simple string to search for
183 * @param bool $confirmed A switch to allow/disallow unconfirmed users
184 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
185 * @param string $sort A SQL snippet for the sorting criteria to use
186 * @param string $firstinitial Users whose first name starts with $firstinitial
187 * @param string $lastinitial Users whose last name starts with $lastinitial
188 * @param string $page The page or records to return
189 * @param string $recordsperpage The number of records to return per page
190 * @param string $fields A comma separated list of fields to be returned from the chosen table.
191 * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
192 * False is returned if an error is encountered.
194 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
195 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
196 global $DB, $CFG;
198 if ($get && !$recordsperpage) {
199 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
200 'On large installations, this will probably cause an out of memory error. ' .
201 'Please think again and change your code so that it does not try to ' .
202 'load so much data into memory.', DEBUG_DEVELOPER);
205 $fullname = $DB->sql_fullname();
207 $select = " id <> :guestid AND deleted = 0";
208 $params = array('guestid'=>$CFG->siteguest);
210 if (!empty($search)){
211 $search = trim($search);
212 $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
213 $params['search1'] = "%$search%";
214 $params['search2'] = "%$search%";
215 $params['search3'] = "$search";
218 if ($confirmed) {
219 $select .= " AND confirmed = 1";
222 if ($exceptions) {
223 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
224 $params = $params + $eparams;
225 $select .= " AND id $exceptions";
228 if ($firstinitial) {
229 $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
230 $params['fni'] = "$firstinitial%";
232 if ($lastinitial) {
233 $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
234 $params['lni'] = "$lastinitial%";
237 if ($extraselect) {
238 $select .= " AND $extraselect";
239 $params = $params + (array)$extraparams;
242 if ($get) {
243 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
244 } else {
245 return $DB->count_records_select('user', $select, $params);
251 * @todo Finish documenting this function
253 * @param string $sort An SQL field to sort by
254 * @param string $dir The sort direction ASC|DESC
255 * @param int $page The page or records to return
256 * @param int $recordsperpage The number of records to return per page
257 * @param string $search A simple string to search for
258 * @param string $firstinitial Users whose first name starts with $firstinitial
259 * @param string $lastinitial Users whose last name starts with $lastinitial
260 * @param string $extraselect An additional SQL select statement to append to the query
261 * @param array $extraparams Additional parameters to use for the above $extraselect
262 * @param object $extracontext If specified, will include user 'extra fields'
263 * as appropriate for current user and given context
264 * @return array Array of {@link $USER} records
266 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
267 $search='', $firstinitial='', $lastinitial='', $extraselect='',
268 array $extraparams=null, $extracontext = null) {
269 global $DB;
271 $fullname = $DB->sql_fullname();
273 $select = "deleted <> 1";
274 $params = array();
276 if (!empty($search)) {
277 $search = trim($search);
278 $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
279 " OR ". $DB->sql_like('email', ':search2', false, false).
280 " OR username = :search3)";
281 $params['search1'] = "%$search%";
282 $params['search2'] = "%$search%";
283 $params['search3'] = "$search";
286 if ($firstinitial) {
287 $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
288 $params['fni'] = "$firstinitial%";
290 if ($lastinitial) {
291 $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
292 $params['lni'] = "$lastinitial%";
295 if ($extraselect) {
296 $select .= " AND $extraselect";
297 $params = $params + (array)$extraparams;
300 if ($sort) {
301 $sort = " ORDER BY $sort $dir";
304 // If a context is specified, get extra user fields that the current user
305 // is supposed to see.
306 $extrafields = '';
307 if ($extracontext) {
308 $extrafields = get_extra_user_fields_sql($extracontext, '', '',
309 array('id', 'username', 'email', 'firstname', 'lastname', 'city', 'country',
310 'lastaccess', 'confirmed', 'mnethostid'));
313 // warning: will return UNCONFIRMED USERS
314 return $DB->get_records_sql("SELECT id, username, email, firstname, lastname, city, country,
315 lastaccess, confirmed, mnethostid, suspended $extrafields
316 FROM {user}
317 WHERE $select
318 $sort", $params, $page, $recordsperpage);
324 * Full list of users that have confirmed their accounts.
326 * @global object
327 * @return array of unconfirmed users
329 function get_users_confirmed() {
330 global $DB, $CFG;
331 return $DB->get_records_sql("SELECT *
332 FROM {user}
333 WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
337 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
341 * Returns $course object of the top-level site.
343 * @return object A {@link $COURSE} object for the site, exception if not found
345 function get_site() {
346 global $SITE, $DB;
348 if (!empty($SITE->id)) { // We already have a global to use, so return that
349 return $SITE;
352 if ($course = $DB->get_record('course', array('category'=>0))) {
353 return $course;
354 } else {
355 // course table exists, but the site is not there,
356 // unfortunately there is no automatic way to recover
357 throw new moodle_exception('nosite', 'error');
362 * Returns list of courses, for whole site, or category
364 * Returns list of courses, for whole site, or category
365 * Important: Using c.* for fields is extremely expensive because
366 * we are using distinct. You almost _NEVER_ need all the fields
367 * in such a large SELECT
369 * @global object
370 * @global object
371 * @global object
372 * @uses CONTEXT_COURSE
373 * @param string|int $categoryid Either a category id or 'all' for everything
374 * @param string $sort A field and direction to sort by
375 * @param string $fields The additional fields to return
376 * @return array Array of courses
378 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
380 global $USER, $CFG, $DB;
382 $params = array();
384 if ($categoryid !== "all" && is_numeric($categoryid)) {
385 $categoryselect = "WHERE c.category = :catid";
386 $params['catid'] = $categoryid;
387 } else {
388 $categoryselect = "";
391 if (empty($sort)) {
392 $sortstatement = "";
393 } else {
394 $sortstatement = "ORDER BY $sort";
397 $visiblecourses = array();
399 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
401 $sql = "SELECT $fields $ccselect
402 FROM {course} c
403 $ccjoin
404 $categoryselect
405 $sortstatement";
407 // pull out all course matching the cat
408 if ($courses = $DB->get_records_sql($sql, $params)) {
410 // loop throught them
411 foreach ($courses as $course) {
412 context_instance_preload($course);
413 if (isset($course->visible) && $course->visible <= 0) {
414 // for hidden courses, require visibility check
415 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
416 $visiblecourses [$course->id] = $course;
418 } else {
419 $visiblecourses [$course->id] = $course;
423 return $visiblecourses;
428 * Returns list of courses, for whole site, or category
430 * Similar to get_courses, but allows paging
431 * Important: Using c.* for fields is extremely expensive because
432 * we are using distinct. You almost _NEVER_ need all the fields
433 * in such a large SELECT
435 * @global object
436 * @global object
437 * @global object
438 * @uses CONTEXT_COURSE
439 * @param string|int $categoryid Either a category id or 'all' for everything
440 * @param string $sort A field and direction to sort by
441 * @param string $fields The additional fields to return
442 * @param int $totalcount Reference for the number of courses
443 * @param string $limitfrom The course to start from
444 * @param string $limitnum The number of courses to limit to
445 * @return array Array of courses
447 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
448 &$totalcount, $limitfrom="", $limitnum="") {
449 global $USER, $CFG, $DB;
451 $params = array();
453 $categoryselect = "";
454 if ($categoryid != "all" && is_numeric($categoryid)) {
455 $categoryselect = "WHERE c.category = :catid";
456 $params['catid'] = $categoryid;
457 } else {
458 $categoryselect = "";
461 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
463 $totalcount = 0;
464 if (!$limitfrom) {
465 $limitfrom = 0;
467 $visiblecourses = array();
469 $sql = "SELECT $fields $ccselect
470 FROM {course} c
471 $ccjoin
472 $categoryselect
473 ORDER BY $sort";
475 // pull out all course matching the cat
476 $rs = $DB->get_recordset_sql($sql, $params);
477 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
478 foreach($rs as $course) {
479 context_instance_preload($course);
480 if ($course->visible <= 0) {
481 // for hidden courses, require visibility check
482 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
483 $totalcount++;
484 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
485 $visiblecourses [$course->id] = $course;
488 } else {
489 $totalcount++;
490 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
491 $visiblecourses [$course->id] = $course;
495 $rs->close();
496 return $visiblecourses;
500 * Retrieve course records with the course managers and other related records
501 * that we need for print_course(). This allows print_courses() to do its job
502 * in a constant number of DB queries, regardless of the number of courses,
503 * role assignments, etc.
505 * The returned array is indexed on c.id, and each course will have
506 * - $course->managers - array containing RA objects that include a $user obj
507 * with the minimal fields needed for fullname()
509 * @global object
510 * @global object
511 * @global object
512 * @uses CONTEXT_COURSE
513 * @uses CONTEXT_SYSTEM
514 * @uses CONTEXT_COURSECAT
515 * @uses SITEID
516 * @param int|string $categoryid Either the categoryid for the courses or 'all'
517 * @param string $sort A SQL sort field and direction
518 * @param array $fields An array of additional fields to fetch
519 * @return array
521 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
523 * The plan is to
525 * - Grab the courses JOINed w/context
527 * - Grab the interesting course-manager RAs
528 * JOINed with a base user obj and add them to each course
530 * So as to do all the work in 2 DB queries. The RA+user JOIN
531 * ends up being pretty expensive if it happens over _all_
532 * courses on a large site. (Are we surprised!?)
534 * So this should _never_ get called with 'all' on a large site.
537 global $USER, $CFG, $DB;
539 $params = array();
540 $allcats = false; // bool flag
541 if ($categoryid === 'all') {
542 $categoryclause = '';
543 $allcats = true;
544 } elseif (is_numeric($categoryid)) {
545 $categoryclause = "c.category = :catid";
546 $params['catid'] = $categoryid;
547 } else {
548 debugging("Could not recognise categoryid = $categoryid");
549 $categoryclause = '';
552 $basefields = array('id', 'category', 'sortorder',
553 'shortname', 'fullname', 'idnumber',
554 'startdate', 'visible',
555 'newsitems', 'groupmode', 'groupmodeforce');
557 if (!is_null($fields) && is_string($fields)) {
558 if (empty($fields)) {
559 $fields = $basefields;
560 } else {
561 // turn the fields from a string to an array that
562 // get_user_courses_bycap() will like...
563 $fields = explode(',',$fields);
564 $fields = array_map('trim', $fields);
565 $fields = array_unique(array_merge($basefields, $fields));
567 } elseif (is_array($fields)) {
568 $fields = array_merge($basefields,$fields);
570 $coursefields = 'c.' .join(',c.', $fields);
572 if (empty($sort)) {
573 $sortstatement = "";
574 } else {
575 $sortstatement = "ORDER BY $sort";
578 $where = 'WHERE c.id != ' . SITEID;
579 if ($categoryclause !== ''){
580 $where = "$where AND $categoryclause";
583 // pull out all courses matching the cat
584 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
585 $sql = "SELECT $coursefields $ccselect
586 FROM {course} c
587 $ccjoin
588 $where
589 $sortstatement";
591 $catpaths = array();
592 $catpath = NULL;
593 if ($courses = $DB->get_records_sql($sql, $params)) {
594 // loop on courses materialising
595 // the context, and prepping data to fetch the
596 // managers efficiently later...
597 foreach ($courses as $k => $course) {
598 context_instance_preload($course);
599 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
600 $courses[$k] = $course;
601 $courses[$k]->managers = array();
602 if ($allcats === false) {
603 // single cat, so take just the first one...
604 if ($catpath === NULL) {
605 $catpath = preg_replace(':/\d+$:', '', $coursecontext->path);
607 } else {
608 // chop off the contextid of the course itself
609 // like dirname() does...
610 $catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path);
613 } else {
614 return array(); // no courses!
617 $CFG->coursecontact = trim($CFG->coursecontact);
618 if (empty($CFG->coursecontact)) {
619 return $courses;
622 $managerroles = explode(',', $CFG->coursecontact);
623 $catctxids = '';
624 if (count($managerroles)) {
625 if ($allcats === true) {
626 $catpaths = array_unique($catpaths);
627 $ctxids = array();
628 foreach ($catpaths as $cpath) {
629 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
631 $ctxids = array_unique($ctxids);
632 $catctxids = implode( ',' , $ctxids);
633 unset($catpaths);
634 unset($cpath);
635 } else {
636 // take the ctx path from the first course
637 // as all categories will be the same...
638 $catpath = substr($catpath,1);
639 $catpath = preg_replace(':/\d+$:','',$catpath);
640 $catctxids = str_replace('/',',',$catpath);
642 if ($categoryclause !== '') {
643 $categoryclause = "AND $categoryclause";
646 * Note: Here we use a LEFT OUTER JOIN that can
647 * "optionally" match to avoid passing a ton of context
648 * ids in an IN() clause. Perhaps a subselect is faster.
650 * In any case, this SQL is not-so-nice over large sets of
651 * courses with no $categoryclause.
654 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
655 r.id AS roleid, r.name as rolename,
656 u.id AS userid, u.firstname, u.lastname
657 FROM {role_assignments} ra
658 JOIN {context} ctx ON ra.contextid = ctx.id
659 JOIN {user} u ON ra.userid = u.id
660 JOIN {role} r ON ra.roleid = r.id
661 LEFT OUTER JOIN {course} c
662 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
663 WHERE ( c.id IS NOT NULL";
664 // under certain conditions, $catctxids is NULL
665 if($catctxids == NULL){
666 $sql .= ") ";
667 }else{
668 $sql .= " OR ra.contextid IN ($catctxids) )";
671 $sql .= "AND ra.roleid IN ({$CFG->coursecontact})
672 $categoryclause
673 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
674 $rs = $DB->get_recordset_sql($sql, $params);
676 // This loop is fairly stupid as it stands - might get better
677 // results doing an initial pass clustering RAs by path.
678 foreach($rs as $ra) {
679 $user = new stdClass;
680 $user->id = $ra->userid; unset($ra->userid);
681 $user->firstname = $ra->firstname; unset($ra->firstname);
682 $user->lastname = $ra->lastname; unset($ra->lastname);
683 $ra->user = $user;
684 if ($ra->contextlevel == CONTEXT_SYSTEM) {
685 foreach ($courses as $k => $course) {
686 $courses[$k]->managers[] = $ra;
688 } else if ($ra->contextlevel == CONTEXT_COURSECAT) {
689 if ($allcats === false) {
690 // It always applies
691 foreach ($courses as $k => $course) {
692 $courses[$k]->managers[] = $ra;
694 } else {
695 foreach ($courses as $k => $course) {
696 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
697 // Note that strpos() returns 0 as "matched at pos 0"
698 if (strpos($coursecontext->path, $ra->path.'/') === 0) {
699 // Only add it to subpaths
700 $courses[$k]->managers[] = $ra;
704 } else { // course-level
705 if (!array_key_exists($ra->instanceid, $courses)) {
706 //this course is not in a list, probably a frontpage course
707 continue;
709 $courses[$ra->instanceid]->managers[] = $ra;
712 $rs->close();
715 return $courses;
719 * A list of courses that match a search
721 * @global object
722 * @global object
723 * @param array $searchterms An array of search criteria
724 * @param string $sort A field and direction to sort by
725 * @param int $page The page number to get
726 * @param int $recordsperpage The number of records per page
727 * @param int $totalcount Passed in by reference.
728 * @return object {@link $COURSE} records
730 function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
731 global $CFG, $DB;
733 if ($DB->sql_regex_supported()) {
734 $REGEXP = $DB->sql_regex(true);
735 $NOTREGEXP = $DB->sql_regex(false);
738 $searchcond = array();
739 $params = array();
740 $i = 0;
742 // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
743 if ($DB->get_dbfamily() == 'oracle') {
744 $concat = $DB->sql_concat('c.summary', "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
745 } else {
746 $concat = $DB->sql_concat("COALESCE(c.summary, '". $DB->sql_empty() ."')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
749 foreach ($searchterms as $searchterm) {
750 $i++;
752 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
753 /// will use it to simulate the "-" operator with LIKE clause
755 /// Under Oracle and MSSQL, trim the + and - operators and perform
756 /// simpler LIKE (or NOT LIKE) queries
757 if (!$DB->sql_regex_supported()) {
758 if (substr($searchterm, 0, 1) == '-') {
759 $NOT = true;
761 $searchterm = trim($searchterm, '+-');
764 // TODO: +- may not work for non latin languages
766 if (substr($searchterm,0,1) == '+') {
767 $searchterm = trim($searchterm, '+-');
768 $searchterm = preg_quote($searchterm, '|');
769 $searchcond[] = "$concat $REGEXP :ss$i";
770 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
772 } else if (substr($searchterm,0,1) == "-") {
773 $searchterm = trim($searchterm, '+-');
774 $searchterm = preg_quote($searchterm, '|');
775 $searchcond[] = "$concat $NOTREGEXP :ss$i";
776 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
778 } else {
779 $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
780 $params['ss'.$i] = "%$searchterm%";
784 if (empty($searchcond)) {
785 $totalcount = 0;
786 return array();
789 $searchcond = implode(" AND ", $searchcond);
791 $courses = array();
792 $c = 0; // counts how many visible courses we've seen
794 // Tiki pagination
795 $limitfrom = $page * $recordsperpage;
796 $limitto = $limitfrom + $recordsperpage;
798 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
799 $sql = "SELECT c.* $ccselect
800 FROM {course} c
801 $ccjoin
802 WHERE $searchcond AND c.id <> ".SITEID."
803 ORDER BY $sort";
805 $rs = $DB->get_recordset_sql($sql, $params);
806 foreach($rs as $course) {
807 context_instance_preload($course);
808 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
809 if ($course->visible || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
810 // Don't exit this loop till the end
811 // we need to count all the visible courses
812 // to update $totalcount
813 if ($c >= $limitfrom && $c < $limitto) {
814 $courses[$course->id] = $course;
816 $c++;
819 $rs->close();
821 // our caller expects 2 bits of data - our return
822 // array, and an updated $totalcount
823 $totalcount = $c;
824 return $courses;
829 * Returns a sorted list of categories. Each category object has a context
830 * property that is a context object.
832 * When asking for $parent='none' it will return all the categories, regardless
833 * of depth. Wheen asking for a specific parent, the default is to return
834 * a "shallow" resultset. Pass false to $shallow and it will return all
835 * the child categories as well.
837 * @global object
838 * @uses CONTEXT_COURSECAT
839 * @param string $parent The parent category if any
840 * @param string $sort the sortorder
841 * @param bool $shallow - set to false to get the children too
842 * @return array of categories
844 function get_categories($parent='none', $sort=NULL, $shallow=true) {
845 global $DB;
847 if ($sort === NULL) {
848 $sort = 'ORDER BY cc.sortorder ASC';
849 } elseif ($sort ==='') {
850 // leave it as empty
851 } else {
852 $sort = "ORDER BY $sort";
855 list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
857 if ($parent === 'none') {
858 $sql = "SELECT cc.* $ccselect
859 FROM {course_categories} cc
860 $ccjoin
861 $sort";
862 $params = array();
864 } elseif ($shallow) {
865 $sql = "SELECT cc.* $ccselect
866 FROM {course_categories} cc
867 $ccjoin
868 WHERE cc.parent=?
869 $sort";
870 $params = array($parent);
872 } else {
873 $sql = "SELECT cc.* $ccselect
874 FROM {course_categories} cc
875 $ccjoin
876 JOIN {course_categories} ccp
877 ON ((cc.parent = ccp.id) OR (cc.path LIKE ".$DB->sql_concat('ccp.path',"'/%'")."))
878 WHERE ccp.id=?
879 $sort";
880 $params = array($parent);
882 $categories = array();
884 $rs = $DB->get_recordset_sql($sql, $params);
885 foreach($rs as $cat) {
886 context_instance_preload($cat);
887 $catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->id);
888 if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) {
889 $categories[$cat->id] = $cat;
892 $rs->close();
893 return $categories;
898 * Returns an array of category ids of all the subcategories for a given
899 * category.
901 * @global object
902 * @param int $catid - The id of the category whose subcategories we want to find.
903 * @return array of category ids.
905 function get_all_subcategories($catid) {
906 global $DB;
908 $subcats = array();
910 if ($categories = $DB->get_records('course_categories', array('parent'=>$catid))) {
911 foreach ($categories as $cat) {
912 array_push($subcats, $cat->id);
913 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
916 return $subcats;
920 * Return specified category, default if given does not exist
922 * @global object
923 * @uses MAX_COURSES_IN_CATEGORY
924 * @uses CONTEXT_COURSECAT
925 * @uses SYSCONTEXTID
926 * @param int $catid course category id
927 * @return object caregory
929 function get_course_category($catid=0) {
930 global $DB;
932 $category = false;
934 if (!empty($catid)) {
935 $category = $DB->get_record('course_categories', array('id'=>$catid));
938 if (!$category) {
939 // the first category is considered default for now
940 if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
941 $category = reset($category);
943 } else {
944 $cat = new stdClass();
945 $cat->name = get_string('miscellaneous');
946 $cat->depth = 1;
947 $cat->sortorder = MAX_COURSES_IN_CATEGORY;
948 $cat->timemodified = time();
949 $catid = $DB->insert_record('course_categories', $cat);
950 // make sure category context exists
951 get_context_instance(CONTEXT_COURSECAT, $catid);
952 mark_context_dirty('/'.SYSCONTEXTID);
953 fix_course_sortorder(); // Required to build course_categories.depth and .path.
954 $category = $DB->get_record('course_categories', array('id'=>$catid));
958 return $category;
962 * Fixes course category and course sortorder, also verifies category and course parents and paths.
963 * (circular references are not fixed)
965 * @global object
966 * @global object
967 * @uses MAX_COURSES_IN_CATEGORY
968 * @uses MAX_COURSE_CATEGORIES
969 * @uses SITEID
970 * @uses CONTEXT_COURSE
971 * @return void
973 function fix_course_sortorder() {
974 global $DB, $SITE;
976 //WARNING: this is PHP5 only code!
978 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
979 //move all categories that are not sorted yet to the end
980 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
983 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
984 $topcats = array();
985 $brokencats = array();
986 foreach ($allcats as $cat) {
987 $sortorder = (int)$cat->sortorder;
988 if (!$cat->parent) {
989 while(isset($topcats[$sortorder])) {
990 $sortorder++;
992 $topcats[$sortorder] = $cat;
993 continue;
995 if (!isset($allcats[$cat->parent])) {
996 $brokencats[] = $cat;
997 continue;
999 if (!isset($allcats[$cat->parent]->children)) {
1000 $allcats[$cat->parent]->children = array();
1002 while(isset($allcats[$cat->parent]->children[$sortorder])) {
1003 $sortorder++;
1005 $allcats[$cat->parent]->children[$sortorder] = $cat;
1007 unset($allcats);
1009 // add broken cats to category tree
1010 if ($brokencats) {
1011 $defaultcat = reset($topcats);
1012 foreach ($brokencats as $cat) {
1013 $topcats[] = $cat;
1017 // now walk recursively the tree and fix any problems found
1018 $sortorder = 0;
1019 $fixcontexts = array();
1020 _fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts);
1022 // detect if there are "multiple" frontpage courses and fix them if needed
1023 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
1024 if (count($frontcourses) > 1) {
1025 if (isset($frontcourses[SITEID])) {
1026 $frontcourse = $frontcourses[SITEID];
1027 unset($frontcourses[SITEID]);
1028 } else {
1029 $frontcourse = array_shift($frontcourses);
1031 $defaultcat = reset($topcats);
1032 foreach ($frontcourses as $course) {
1033 $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
1034 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1035 $fixcontexts[$context->id] = $context;
1037 unset($frontcourses);
1038 } else {
1039 $frontcourse = reset($frontcourses);
1042 // now fix the paths and depths in context table if needed
1043 if ($fixcontexts) {
1044 foreach ($fixcontexts as $fixcontext) {
1045 $fixcontext->reset_paths(false);
1047 context_helper::build_all_paths(false);
1048 unset($fixcontexts);
1051 // release memory
1052 unset($topcats);
1053 unset($brokencats);
1054 unset($fixcontexts);
1056 // fix frontpage course sortorder
1057 if ($frontcourse->sortorder != 1) {
1058 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
1061 // now fix the course counts in category records if needed
1062 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
1063 FROM {course_categories} cc
1064 LEFT JOIN {course} c ON c.category = cc.id
1065 GROUP BY cc.id, cc.coursecount
1066 HAVING cc.coursecount <> COUNT(c.id)";
1068 if ($updatecounts = $DB->get_records_sql($sql)) {
1069 // categories with more courses than MAX_COURSES_IN_CATEGORY
1070 $categories = array();
1071 foreach ($updatecounts as $cat) {
1072 $cat->coursecount = $cat->newcount;
1073 if ($cat->coursecount >= MAX_COURSES_IN_CATEGORY) {
1074 $categories[] = $cat->id;
1076 unset($cat->newcount);
1077 $DB->update_record_raw('course_categories', $cat, true);
1079 if (!empty($categories)) {
1080 $str = implode(', ', $categories);
1081 debugging("The number of courses (category id: $str) has reached MAX_COURSES_IN_CATEGORY (" . MAX_COURSES_IN_CATEGORY . "), it will cause a sorting performance issue, please increase the value of MAX_COURSES_IN_CATEGORY in lib/datalib.php file. See tracker issue: MDL-25669", DEBUG_DEVELOPER);
1085 // now make sure that sortorders in course table are withing the category sortorder ranges
1086 $sql = "SELECT DISTINCT cc.id, cc.sortorder
1087 FROM {course_categories} cc
1088 JOIN {course} c ON c.category = cc.id
1089 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
1091 if ($fixcategories = $DB->get_records_sql($sql)) {
1092 //fix the course sortorder ranges
1093 foreach ($fixcategories as $cat) {
1094 $sql = "UPDATE {course}
1095 SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
1096 WHERE category = ?";
1097 $DB->execute($sql, array($cat->sortorder, $cat->id));
1100 unset($fixcategories);
1102 // categories having courses with sortorder duplicates or having gaps in sortorder
1103 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
1104 FROM {course} c1
1105 JOIN {course} c2 ON c1.sortorder = c2.sortorder
1106 JOIN {course_categories} cc ON (c1.category = cc.id)
1107 WHERE c1.id <> c2.id";
1108 $fixcategories = $DB->get_records_sql($sql);
1110 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
1111 FROM {course_categories} cc
1112 JOIN {course} c ON c.category = cc.id
1113 GROUP BY cc.id, cc.sortorder, cc.coursecount
1114 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
1115 $gapcategories = $DB->get_records_sql($sql);
1117 foreach ($gapcategories as $cat) {
1118 if (isset($fixcategories[$cat->id])) {
1119 // duplicates detected already
1121 } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
1122 // easy - new course inserted with sortorder 0, the rest is ok
1123 $sql = "UPDATE {course}
1124 SET sortorder = sortorder + 1
1125 WHERE category = ?";
1126 $DB->execute($sql, array($cat->id));
1128 } else {
1129 // it needs full resorting
1130 $fixcategories[$cat->id] = $cat;
1133 unset($gapcategories);
1135 // fix course sortorders in problematic categories only
1136 foreach ($fixcategories as $cat) {
1137 $i = 1;
1138 $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1139 foreach ($courses as $course) {
1140 if ($course->sortorder != $cat->sortorder + $i) {
1141 $course->sortorder = $cat->sortorder + $i;
1142 $DB->update_record_raw('course', $course, true);
1144 $i++;
1150 * Internal recursive category verification function, do not use directly!
1152 * @todo Document the arguments of this function better
1154 * @global object
1155 * @uses MAX_COURSES_IN_CATEGORY
1156 * @uses CONTEXT_COURSECAT
1157 * @param array $children
1158 * @param int $sortorder
1159 * @param string $parent
1160 * @param int $depth
1161 * @param string $path
1162 * @param array $fixcontexts
1163 * @return void
1165 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1166 global $DB;
1168 $depth++;
1170 foreach ($children as $cat) {
1171 $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1172 $update = false;
1173 if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1174 $cat->parent = $parent;
1175 $cat->depth = $depth;
1176 $cat->path = $path.'/'.$cat->id;
1177 $update = true;
1179 // make sure context caches are rebuild and dirty contexts marked
1180 $context = get_context_instance(CONTEXT_COURSECAT, $cat->id);
1181 $fixcontexts[$context->id] = $context;
1183 if ($cat->sortorder != $sortorder) {
1184 $cat->sortorder = $sortorder;
1185 $update = true;
1187 if ($update) {
1188 $DB->update_record('course_categories', $cat, true);
1190 if (isset($cat->children)) {
1191 _fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts);
1197 * List of remote courses that a user has access to via MNET.
1198 * Works only on the IDP
1200 * @global object
1201 * @global object
1202 * @param int @userid The user id to get remote courses for
1203 * @return array Array of {@link $COURSE} of course objects
1205 function get_my_remotecourses($userid=0) {
1206 global $DB, $USER;
1208 if (empty($userid)) {
1209 $userid = $USER->id;
1212 // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1213 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1214 c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1215 h.name AS hostname
1216 FROM {mnetservice_enrol_courses} c
1217 JOIN (SELECT DISTINCT hostid, remotecourseid
1218 FROM {mnetservice_enrol_enrolments}
1219 WHERE userid = ?
1220 ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1221 JOIN {mnet_host} h ON h.id = c.hostid";
1223 return $DB->get_records_sql($sql, array($userid));
1227 * List of remote hosts that a user has access to via MNET.
1228 * Works on the SP
1230 * @global object
1231 * @global object
1232 * @return array|bool Array of host objects or false
1234 function get_my_remotehosts() {
1235 global $CFG, $USER;
1237 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1238 return false; // Return nothing on the IDP
1240 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1241 return $USER->mnet_foreign_host_array;
1243 return false;
1247 * This function creates a default separated/connected scale
1249 * This function creates a default separated/connected scale
1250 * so there's something in the database. The locations of
1251 * strings and files is a bit odd, but this is because we
1252 * need to maintain backward compatibility with many different
1253 * existing language translations and older sites.
1255 * @global object
1256 * @return void
1258 function make_default_scale() {
1259 global $DB;
1261 $defaultscale = new stdClass();
1262 $defaultscale->courseid = 0;
1263 $defaultscale->userid = 0;
1264 $defaultscale->name = get_string('separateandconnected');
1265 $defaultscale->description = get_string('separateandconnectedinfo');
1266 $defaultscale->scale = get_string('postrating1', 'forum').','.
1267 get_string('postrating2', 'forum').','.
1268 get_string('postrating3', 'forum');
1269 $defaultscale->timemodified = time();
1271 $defaultscale->id = $DB->insert_record('scale', $defaultscale);
1272 $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id));
1277 * Returns a menu of all available scales from the site as well as the given course
1279 * @global object
1280 * @param int $courseid The id of the course as found in the 'course' table.
1281 * @return array
1283 function get_scales_menu($courseid=0) {
1284 global $DB;
1286 $sql = "SELECT id, name
1287 FROM {scale}
1288 WHERE courseid = 0 or courseid = ?
1289 ORDER BY courseid ASC, name ASC";
1290 $params = array($courseid);
1292 if ($scales = $DB->get_records_sql_menu($sql, $params)) {
1293 return $scales;
1296 make_default_scale();
1298 return $DB->get_records_sql_menu($sql, $params);
1304 * Given a set of timezone records, put them in the database, replacing what is there
1306 * @global object
1307 * @param array $timezones An array of timezone records
1308 * @return void
1310 function update_timezone_records($timezones) {
1311 global $DB;
1313 /// Clear out all the old stuff
1314 $DB->delete_records('timezone');
1316 /// Insert all the new stuff
1317 foreach ($timezones as $timezone) {
1318 if (is_array($timezone)) {
1319 $timezone = (object)$timezone;
1321 $DB->insert_record('timezone', $timezone);
1326 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1329 * Just gets a raw list of all modules in a course
1331 * @global object
1332 * @param int $courseid The id of the course as found in the 'course' table.
1333 * @return array
1335 function get_course_mods($courseid) {
1336 global $DB;
1338 if (empty($courseid)) {
1339 return false; // avoid warnings
1342 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1343 FROM {modules} m, {course_modules} cm
1344 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1345 array($courseid)); // no disabled mods
1350 * Given an id of a course module, finds the coursemodule description
1352 * @global object
1353 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1354 * @param int $cmid course module id (id in course_modules table)
1355 * @param int $courseid optional course id for extra validation
1356 * @param bool $sectionnum include relative section number (0,1,2 ...)
1357 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1358 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1359 * MUST_EXIST means throw exception if no record or multiple records found
1360 * @return stdClass
1362 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1363 global $DB;
1365 $params = array('cmid'=>$cmid);
1367 if (!$modulename) {
1368 if (!$modulename = $DB->get_field_sql("SELECT md.name
1369 FROM {modules} md
1370 JOIN {course_modules} cm ON cm.module = md.id
1371 WHERE cm.id = :cmid", $params, $strictness)) {
1372 return false;
1376 $params['modulename'] = $modulename;
1378 $courseselect = "";
1379 $sectionfield = "";
1380 $sectionjoin = "";
1382 if ($courseid) {
1383 $courseselect = "AND cm.course = :courseid";
1384 $params['courseid'] = $courseid;
1387 if ($sectionnum) {
1388 $sectionfield = ", cw.section AS sectionnum";
1389 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1392 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1393 FROM {course_modules} cm
1394 JOIN {modules} md ON md.id = cm.module
1395 JOIN {".$modulename."} m ON m.id = cm.instance
1396 $sectionjoin
1397 WHERE cm.id = :cmid AND md.name = :modulename
1398 $courseselect";
1400 return $DB->get_record_sql($sql, $params, $strictness);
1404 * Given an instance number of a module, finds the coursemodule description
1406 * @global object
1407 * @param string $modulename name of module type, eg. resource, assignment,...
1408 * @param int $instance module instance number (id in resource, assignment etc. table)
1409 * @param int $courseid optional course id for extra validation
1410 * @param bool $sectionnum include relative section number (0,1,2 ...)
1411 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1412 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1413 * MUST_EXIST means throw exception if no record or multiple records found
1414 * @return stdClass
1416 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1417 global $DB;
1419 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1421 $courseselect = "";
1422 $sectionfield = "";
1423 $sectionjoin = "";
1425 if ($courseid) {
1426 $courseselect = "AND cm.course = :courseid";
1427 $params['courseid'] = $courseid;
1430 if ($sectionnum) {
1431 $sectionfield = ", cw.section AS sectionnum";
1432 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1435 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1436 FROM {course_modules} cm
1437 JOIN {modules} md ON md.id = cm.module
1438 JOIN {".$modulename."} m ON m.id = cm.instance
1439 $sectionjoin
1440 WHERE m.id = :instance AND md.name = :modulename
1441 $courseselect";
1443 return $DB->get_record_sql($sql, $params, $strictness);
1447 * Returns all course modules of given activity in course
1449 * @param string $modulename The module name (forum, quiz, etc.)
1450 * @param int $courseid The course id to get modules for
1451 * @param string $extrafields extra fields starting with m.
1452 * @return array Array of results
1454 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1455 global $DB;
1457 if (!empty($extrafields)) {
1458 $extrafields = ", $extrafields";
1460 $params = array();
1461 $params['courseid'] = $courseid;
1462 $params['modulename'] = $modulename;
1465 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1466 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1467 WHERE cm.course = :courseid AND
1468 cm.instance = m.id AND
1469 md.name = :modulename AND
1470 md.id = cm.module", $params);
1474 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1476 * Returns an array of all the active instances of a particular
1477 * module in given courses, sorted in the order they are defined
1478 * in the course. Returns an empty array on any errors.
1480 * The returned objects includle the columns cw.section, cm.visible,
1481 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1483 * @global object
1484 * @global object
1485 * @param string $modulename The name of the module to get instances for
1486 * @param array $courses an array of course objects.
1487 * @param int $userid
1488 * @param int $includeinvisible
1489 * @return array of module instance objects, including some extra fields from the course_modules
1490 * and course_sections tables, or an empty array if an error occurred.
1492 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1493 global $CFG, $DB;
1495 $outputarray = array();
1497 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1498 return $outputarray;
1501 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1502 $params['modulename'] = $modulename;
1504 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1505 cm.groupmode, cm.groupingid, cm.groupmembersonly
1506 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1507 {".$modulename."} m
1508 WHERE cm.course $coursessql AND
1509 cm.instance = m.id AND
1510 cm.section = cw.id AND
1511 md.name = :modulename AND
1512 md.id = cm.module", $params)) {
1513 return $outputarray;
1516 foreach ($courses as $course) {
1517 $modinfo = get_fast_modinfo($course, $userid);
1519 if (empty($modinfo->instances[$modulename])) {
1520 continue;
1523 foreach ($modinfo->instances[$modulename] as $cm) {
1524 if (!$includeinvisible and !$cm->uservisible) {
1525 continue;
1527 if (!isset($rawmods[$cm->id])) {
1528 continue;
1530 $instance = $rawmods[$cm->id];
1531 if (!empty($cm->extra)) {
1532 $instance->extra = $cm->extra;
1534 $outputarray[] = $instance;
1538 return $outputarray;
1542 * Returns an array of all the active instances of a particular module in a given course,
1543 * sorted in the order they are defined.
1545 * Returns an array of all the active instances of a particular
1546 * module in a given course, sorted in the order they are defined
1547 * in the course. Returns an empty array on any errors.
1549 * The returned objects includle the columns cw.section, cm.visible,
1550 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1552 * Simply calls {@link all_instances_in_courses()} with a single provided course
1554 * @param string $modulename The name of the module to get instances for
1555 * @param object $course The course obect.
1556 * @return array of module instance objects, including some extra fields from the course_modules
1557 * and course_sections tables, or an empty array if an error occurred.
1558 * @param int $userid
1559 * @param int $includeinvisible
1561 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1562 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1567 * Determine whether a module instance is visible within a course
1569 * Given a valid module object with info about the id and course,
1570 * and the module's type (eg "forum") returns whether the object
1571 * is visible or not, groupmembersonly visibility not tested
1573 * @global object
1575 * @param $moduletype Name of the module eg 'forum'
1576 * @param $module Object which is the instance of the module
1577 * @return bool Success
1579 function instance_is_visible($moduletype, $module) {
1580 global $DB;
1582 if (!empty($module->id)) {
1583 $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1584 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1585 FROM {course_modules} cm, {modules} m
1586 WHERE cm.course = :courseid AND
1587 cm.module = m.id AND
1588 m.name = :moduletype AND
1589 cm.instance = :moduleid", $params)) {
1591 foreach ($records as $record) { // there should only be one - use the first one
1592 return $record->visible;
1596 return true; // visible by default!
1600 * Determine whether a course module is visible within a course,
1601 * this is different from instance_is_visible() - faster and visibility for user
1603 * @global object
1604 * @global object
1605 * @uses DEBUG_DEVELOPER
1606 * @uses CONTEXT_MODULE
1607 * @uses CONDITION_MISSING_EXTRATABLE
1608 * @param object $cm object
1609 * @param int $userid empty means current user
1610 * @return bool Success
1612 function coursemodule_visible_for_user($cm, $userid=0) {
1613 global $USER,$CFG;
1615 if (empty($cm->id)) {
1616 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1617 return false;
1619 if (empty($userid)) {
1620 $userid = $USER->id;
1622 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1623 return false;
1625 if ($CFG->enableavailability) {
1626 require_once($CFG->libdir.'/conditionlib.php');
1627 $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE);
1628 if(!$ci->is_available($cm->availableinfo,false,$userid) and
1629 !has_capability('moodle/course:viewhiddenactivities',
1630 get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1631 return false;
1634 return groups_course_module_visible($cm, $userid);
1640 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1644 * Add an entry to the log table.
1646 * Add an entry to the log table. These are "action" focussed rather
1647 * than web server hits, and provide a way to easily reconstruct what
1648 * any particular student has been doing.
1650 * @package core
1651 * @category log
1652 * @global moodle_database $DB
1653 * @global stdClass $CFG
1654 * @global stdClass $USER
1655 * @uses SITEID
1656 * @uses DEBUG_DEVELOPER
1657 * @uses DEBUG_ALL
1658 * @param int $courseid The course id
1659 * @param string $module The module name e.g. forum, journal, resource, course, user etc
1660 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1661 * @param string $url The file and parameters used to see the results of the action
1662 * @param string $info Additional description information
1663 * @param string $cm The course_module->id if there is one
1664 * @param string $user If log regards $user other than $USER
1665 * @return void
1667 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1668 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1669 // This is for a good reason: it is the most frequently used DB update function,
1670 // so it has been optimised for speed.
1671 global $DB, $CFG, $USER;
1673 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
1674 $cm = 0;
1677 if ($user) {
1678 $userid = $user;
1679 } else {
1680 if (session_is_loggedinas()) { // Don't log
1681 return;
1683 $userid = empty($USER->id) ? '0' : $USER->id;
1686 if (isset($CFG->logguests) and !$CFG->logguests) {
1687 if (!$userid or isguestuser($userid)) {
1688 return;
1692 $REMOTE_ADDR = getremoteaddr();
1694 $timenow = time();
1695 $info = $info;
1696 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1697 $url = html_entity_decode($url);
1698 } else {
1699 $url = '';
1702 // Restrict length of log lines to the space actually available in the
1703 // database so that it doesn't cause a DB error. Log a warning so that
1704 // developers can avoid doing things which are likely to cause this on a
1705 // routine basis.
1706 if(!empty($info) && textlib::strlen($info)>255) {
1707 $info = textlib::substr($info,0,252).'...';
1708 debugging('Warning: logged very long info',DEBUG_DEVELOPER);
1711 // If the 100 field size is changed, also need to alter print_log in course/lib.php
1712 if(!empty($url) && textlib::strlen($url)>100) {
1713 $url = textlib::substr($url,0,97).'...';
1714 debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
1717 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++;};
1719 $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
1720 'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
1722 try {
1723 $DB->insert_record_raw('log', $log, false);
1724 } catch (dml_exception $e) {
1725 debugging('Error: Could not insert a new entry to the Moodle log. '. $e->error, DEBUG_ALL);
1727 // MDL-11893, alert $CFG->supportemail if insert into log failed
1728 if ($CFG->supportemail and empty($CFG->noemailever)) {
1729 // email_to_user is not usable because email_to_user tries to write to the logs table,
1730 // and this will get caught in an infinite loop, if disk is full
1731 $site = get_site();
1732 $subject = 'Insert into log failed at your moodle site '.$site->fullname;
1733 $message = "Insert into log table failed at ". date('l dS \of F Y h:i:s A') .".\n It is possible that your disk is full.\n\n";
1734 $message .= "The failed query parameters are:\n\n" . var_export($log, true);
1736 $lasttime = get_config('admin', 'lastloginserterrormail');
1737 if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
1738 //using email directly rather than messaging as they may not be able to log in to access a message
1739 mail($CFG->supportemail, $subject, $message);
1740 set_config('lastloginserterrormail', time(), 'admin');
1747 * Store user last access times - called when use enters a course or site
1749 * @package core
1750 * @category log
1751 * @global stdClass $USER
1752 * @global stdClass $CFG
1753 * @global moodle_database $DB
1754 * @uses LASTACCESS_UPDATE_SECS
1755 * @uses SITEID
1756 * @param int $courseid empty courseid means site
1757 * @return void
1759 function user_accesstime_log($courseid=0) {
1760 global $USER, $CFG, $DB;
1762 if (!isloggedin() or session_is_loggedinas()) {
1763 // no access tracking
1764 return;
1767 if (empty($courseid)) {
1768 $courseid = SITEID;
1771 $timenow = time();
1773 /// Store site lastaccess time for the current user
1774 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1775 /// Update $USER->lastaccess for next checks
1776 $USER->lastaccess = $timenow;
1778 $last = new stdClass();
1779 $last->id = $USER->id;
1780 $last->lastip = getremoteaddr();
1781 $last->lastaccess = $timenow;
1783 $DB->update_record_raw('user', $last);
1786 if ($courseid == SITEID) {
1787 /// no user_lastaccess for frontpage
1788 return;
1791 /// Store course lastaccess times for the current user
1792 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
1794 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
1796 if ($lastaccess === false) {
1797 // Update course lastaccess for next checks
1798 $USER->currentcourseaccess[$courseid] = $timenow;
1800 $last = new stdClass();
1801 $last->userid = $USER->id;
1802 $last->courseid = $courseid;
1803 $last->timeaccess = $timenow;
1804 $DB->insert_record_raw('user_lastaccess', $last, false);
1806 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
1807 // no need to update now, it was updated recently in concurrent login ;-)
1809 } else {
1810 // Update course lastaccess for next checks
1811 $USER->currentcourseaccess[$courseid] = $timenow;
1813 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
1819 * Select all log records based on SQL criteria
1821 * @package core
1822 * @category log
1823 * @global moodle_database $DB
1824 * @param string $select SQL select criteria
1825 * @param array $params named sql type params
1826 * @param string $order SQL order by clause to sort the records returned
1827 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
1828 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
1829 * @param int $totalcount Passed in by reference.
1830 * @return array
1832 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1833 global $DB;
1835 if ($order) {
1836 $order = "ORDER BY $order";
1839 $selectsql = "";
1840 $countsql = "";
1842 if ($select) {
1843 $select = "WHERE $select";
1846 $sql = "SELECT COUNT(*)
1847 FROM {log} l
1848 $select";
1850 $totalcount = $DB->count_records_sql($sql, $params);
1852 $sql = "SELECT l.*, u.firstname, u.lastname, u.picture
1853 FROM {log} l
1854 LEFT JOIN {user} u ON l.userid = u.id
1855 $select
1856 $order";
1858 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
1863 * Select all log records for a given course and user
1865 * @package core
1866 * @category log
1867 * @global moodle_database $DB
1868 * @uses DAYSECS
1869 * @param int $userid The id of the user as found in the 'user' table.
1870 * @param int $courseid The id of the course as found in the 'course' table.
1871 * @param string $coursestart unix timestamp representing course start date and time.
1872 * @return array
1874 function get_logs_usercourse($userid, $courseid, $coursestart) {
1875 global $DB;
1877 $params = array();
1879 $courseselect = '';
1880 if ($courseid) {
1881 $courseselect = "AND course = :courseid";
1882 $params['courseid'] = $courseid;
1884 $params['userid'] = $userid;
1885 $$coursestart = (int)$coursestart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1887 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
1888 FROM {log}
1889 WHERE userid = :userid
1890 AND time > $coursestart $courseselect
1891 GROUP BY FLOOR((time - $coursestart)/". DAYSECS .")", $params);
1895 * Select all log records for a given course, user, and day
1897 * @package core
1898 * @category log
1899 * @global moodle_database $DB
1900 * @uses HOURSECS
1901 * @param int $userid The id of the user as found in the 'user' table.
1902 * @param int $courseid The id of the course as found in the 'course' table.
1903 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
1904 * @return array
1906 function get_logs_userday($userid, $courseid, $daystart) {
1907 global $DB;
1909 $params = array('userid'=>$userid);
1911 $courseselect = '';
1912 if ($courseid) {
1913 $courseselect = "AND course = :courseid";
1914 $params['courseid'] = $courseid;
1916 $daystart = (int)$daystart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1918 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
1919 FROM {log}
1920 WHERE userid = :userid
1921 AND time > $daystart $courseselect
1922 GROUP BY FLOOR((time - $daystart)/". HOURSECS .") ", $params);
1926 * Returns an object with counts of failed login attempts
1928 * Returns information about failed login attempts. If the current user is
1929 * an admin, then two numbers are returned: the number of attempts and the
1930 * number of accounts. For non-admins, only the attempts on the given user
1931 * are shown.
1933 * @global moodle_database $DB
1934 * @uses CONTEXT_SYSTEM
1935 * @param string $mode Either 'admin' or 'everybody'
1936 * @param string $username The username we are searching for
1937 * @param string $lastlogin The date from which we are searching
1938 * @return int
1940 function count_login_failures($mode, $username, $lastlogin) {
1941 global $DB;
1943 $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
1944 $select = "module='login' AND action='error' AND time > :lastlogin";
1946 $count = new stdClass();
1948 if (is_siteadmin()) {
1949 if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
1950 $count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
1951 return $count;
1953 } else if ($mode == 'everybody') {
1954 if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
1955 return $count;
1958 return NULL;
1962 /// GENERAL HELPFUL THINGS ///////////////////////////////////
1965 * Dumps a given object's information for debugging purposes
1967 * When used in a CLI script, the object's information is written to the standard
1968 * error output stream. When used in a web script, the object is dumped to a
1969 * pre-formatted block with the "notifytiny" CSS class.
1971 * @param mixed $object The data to be printed
1972 * @return void output is echo'd
1974 function print_object($object) {
1976 // we may need a lot of memory here
1977 raise_memory_limit(MEMORY_EXTRA);
1979 if (CLI_SCRIPT) {
1980 fwrite(STDERR, print_r($object, true));
1981 fwrite(STDERR, PHP_EOL);
1982 } else {
1983 echo html_writer::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
1988 * This function is the official hook inside XMLDB stuff to delegate its debug to one
1989 * external function.
1991 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1992 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1994 * @uses DEBUG_DEVELOPER
1995 * @param string $message string contains the error message
1996 * @param object $object object XMLDB object that fired the debug
1998 function xmldb_debug($message, $object) {
2000 debugging($message, DEBUG_DEVELOPER);
2004 * @global object
2005 * @uses CONTEXT_COURSECAT
2006 * @return boolean Whether the user can create courses in any category in the system.
2008 function user_can_create_courses() {
2009 global $DB;
2010 $catsrs = $DB->get_recordset('course_categories');
2011 foreach ($catsrs as $cat) {
2012 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) {
2013 $catsrs->close();
2014 return true;
2017 $catsrs->close();
2018 return false;