MDL-36204 Improve moodle1 conversion of embedded files
[moodle.git] / lib / datalib.php
blob454bc7ec7b8c5c03b11220fa2f137e61a2ac703c
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;
58 static $prevadmins = null;
60 if (empty($CFG->siteadmins)) { // Should not happen on an ordinary site.
61 return false;
64 if (isset($mainadmin) and $prevadmins === $CFG->siteadmins) {
65 return clone($mainadmin);
68 $mainadmin = null;
70 foreach (explode(',', $CFG->siteadmins) as $id) {
71 if ($user = $DB->get_record('user', array('id'=>$id, 'deleted'=>0))) {
72 $mainadmin = $user;
73 break;
77 if ($mainadmin) {
78 $prevadmins = $CFG->siteadmins;
79 return clone($mainadmin);
80 } else {
81 // this should not happen
82 return false;
86 /**
87 * Returns list of all admins, using 1 DB query
89 * @return array
91 function get_admins() {
92 global $DB, $CFG;
94 if (empty($CFG->siteadmins)) { // Should not happen on an ordinary site
95 return array();
98 $sql = "SELECT u.*
99 FROM {user} u
100 WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
102 // We want the same order as in $CFG->siteadmins.
103 $records = $DB->get_records_sql($sql);
104 $admins = array();
105 foreach (explode(',', $CFG->siteadmins) as $id) {
106 $id = (int)$id;
107 if (!isset($records[$id])) {
108 // User does not exist, this should not happen.
109 continue;
111 $admins[$records[$id]->id] = $records[$id];
114 return $admins;
118 * Search through course users
120 * If $coursid specifies the site course then this function searches
121 * through all undeleted and confirmed users
123 * @global object
124 * @uses SITEID
125 * @uses SQL_PARAMS_NAMED
126 * @uses CONTEXT_COURSE
127 * @param int $courseid The course in question.
128 * @param int $groupid The group in question.
129 * @param string $searchtext The string to search for
130 * @param string $sort A field to sort by
131 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
132 * @return array
134 function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
135 global $DB;
137 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
139 if (!empty($exceptions)) {
140 list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
141 $except = "AND u.id $exceptions";
142 } else {
143 $except = "";
144 $params = array();
147 if (!empty($sort)) {
148 $order = "ORDER BY $sort";
149 } else {
150 $order = "";
153 $select = "u.deleted = 0 AND u.confirmed = 1 AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
154 $params['search1'] = "%$searchtext%";
155 $params['search2'] = "%$searchtext%";
157 if (!$courseid or $courseid == SITEID) {
158 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
159 FROM {user} u
160 WHERE $select
161 $except
162 $order";
163 return $DB->get_records_sql($sql, $params);
165 } else {
166 if ($groupid) {
167 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
168 FROM {user} u
169 JOIN {groups_members} gm ON gm.userid = u.id
170 WHERE $select AND gm.groupid = :groupid
171 $except
172 $order";
173 $params['groupid'] = $groupid;
174 return $DB->get_records_sql($sql, $params);
176 } else {
177 $context = context_course::instance($courseid);
178 $contextlists = get_related_contexts_string($context);
180 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
181 FROM {user} u
182 JOIN {role_assignments} ra ON ra.userid = u.id
183 WHERE $select AND ra.contextid $contextlists
184 $except
185 $order";
186 return $DB->get_records_sql($sql, $params);
192 * This function generates the standard ORDER BY clause for use when generating
193 * lists of users. If you don't have a reason to use a different order, then
194 * you should use this method to generate the order when displaying lists of users.
196 * If the optional $search parameter is passed, then exact matches to the search
197 * will be sorted first. For example, suppose you have two users 'Al Zebra' and
198 * 'Alan Aardvark'. The default sort is Alan, then Al. If, however, you search for
199 * 'Al', then Al will be listed first. (With two users, this is not a big deal,
200 * but with thousands of users, it is essential.)
202 * The list of fields scanned for exact matches are:
203 * - firstname
204 * - lastname
205 * - $DB->sql_fullname
206 * - those returned by get_extra_user_fields
208 * If named parameters are used (which is the default, and highly recommended),
209 * then the parameter names are like :usersortexactN, where N is an int.
211 * The simplest possible example use is:
212 * list($sort, $params) = users_order_by_sql();
213 * $sql = 'SELECT * FROM {users} ORDER BY ' . $sort;
215 * A more complex example, showing that this sort can be combined with other sorts:
216 * list($sort, $sortparams) = users_order_by_sql('u');
217 * $sql = "SELECT g.id AS groupid, gg.groupingid, u.id AS userid, u.firstname, u.lastname, u.idnumber, u.username
218 * FROM {groups} g
219 * LEFT JOIN {groupings_groups} gg ON g.id = gg.groupid
220 * LEFT JOIN {groups_members} gm ON g.id = gm.groupid
221 * LEFT JOIN {user} u ON gm.userid = u.id
222 * WHERE g.courseid = :courseid $groupwhere $groupingwhere
223 * ORDER BY g.name, $sort";
224 * $params += $sortparams;
226 * An example showing the use of $search:
227 * list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
228 * $order = ' ORDER BY ' . $sort;
229 * $params += $sortparams;
230 * $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
232 * @param string $usertablealias (optional) any table prefix for the {users} table. E.g. 'u'.
233 * @param string $search (optional) a current search string. If given,
234 * any exact matches to this string will be sorted first.
235 * @param context $context the context we are in. Use by get_extra_user_fields.
236 * Defaults to $PAGE->context.
237 * @return array with two elements:
238 * string SQL fragment to use in the ORDER BY clause. For example, "firstname, lastname".
239 * array of parameters used in the SQL fragment.
241 function users_order_by_sql($usertablealias = '', $search = null, context $context = null) {
242 global $DB, $PAGE;
244 if ($usertablealias) {
245 $tableprefix = $usertablealias . '.';
246 } else {
247 $tableprefix = '';
250 $sort = "{$tableprefix}lastname, {$tableprefix}firstname, {$tableprefix}id";
251 $params = array();
253 if (!$search) {
254 return array($sort, $params);
257 if (!$context) {
258 $context = $PAGE->context;
261 $exactconditions = array();
262 $paramkey = 'usersortexact1';
264 $exactconditions[] = $DB->sql_fullname($tableprefix . 'firstname', $tableprefix . 'lastname') .
265 ' = :' . $paramkey;
266 $params[$paramkey] = $search;
267 $paramkey++;
269 $fieldstocheck = array_merge(array('firstname', 'lastname'), get_extra_user_fields($context));
270 foreach ($fieldstocheck as $key => $field) {
271 $exactconditions[] = 'LOWER(' . $tableprefix . $field . ') = LOWER(:' . $paramkey . ')';
272 $params[$paramkey] = $search;
273 $paramkey++;
276 $sort = 'CASE WHEN ' . implode(' OR ', $exactconditions) .
277 ' THEN 0 ELSE 1 END, ' . $sort;
279 return array($sort, $params);
283 * Returns a subset of users
285 * @global object
286 * @uses DEBUG_DEVELOPER
287 * @uses SQL_PARAMS_NAMED
288 * @param bool $get If false then only a count of the records is returned
289 * @param string $search A simple string to search for
290 * @param bool $confirmed A switch to allow/disallow unconfirmed users
291 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
292 * @param string $sort A SQL snippet for the sorting criteria to use
293 * @param string $firstinitial Users whose first name starts with $firstinitial
294 * @param string $lastinitial Users whose last name starts with $lastinitial
295 * @param string $page The page or records to return
296 * @param string $recordsperpage The number of records to return per page
297 * @param string $fields A comma separated list of fields to be returned from the chosen table.
298 * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
299 * False is returned if an error is encountered.
301 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
302 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
303 global $DB, $CFG;
305 if ($get && !$recordsperpage) {
306 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
307 'On large installations, this will probably cause an out of memory error. ' .
308 'Please think again and change your code so that it does not try to ' .
309 'load so much data into memory.', DEBUG_DEVELOPER);
312 $fullname = $DB->sql_fullname();
314 $select = " id <> :guestid AND deleted = 0";
315 $params = array('guestid'=>$CFG->siteguest);
317 if (!empty($search)){
318 $search = trim($search);
319 $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
320 $params['search1'] = "%$search%";
321 $params['search2'] = "%$search%";
322 $params['search3'] = "$search";
325 if ($confirmed) {
326 $select .= " AND confirmed = 1";
329 if ($exceptions) {
330 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
331 $params = $params + $eparams;
332 $select .= " AND id $exceptions";
335 if ($firstinitial) {
336 $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
337 $params['fni'] = "$firstinitial%";
339 if ($lastinitial) {
340 $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
341 $params['lni'] = "$lastinitial%";
344 if ($extraselect) {
345 $select .= " AND $extraselect";
346 $params = $params + (array)$extraparams;
349 if ($get) {
350 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
351 } else {
352 return $DB->count_records_select('user', $select, $params);
358 * @todo Finish documenting this function
360 * @param string $sort An SQL field to sort by
361 * @param string $dir The sort direction ASC|DESC
362 * @param int $page The page or records to return
363 * @param int $recordsperpage The number of records to return per page
364 * @param string $search A simple string to search for
365 * @param string $firstinitial Users whose first name starts with $firstinitial
366 * @param string $lastinitial Users whose last name starts with $lastinitial
367 * @param string $extraselect An additional SQL select statement to append to the query
368 * @param array $extraparams Additional parameters to use for the above $extraselect
369 * @param object $extracontext If specified, will include user 'extra fields'
370 * as appropriate for current user and given context
371 * @return array Array of {@link $USER} records
373 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
374 $search='', $firstinitial='', $lastinitial='', $extraselect='',
375 array $extraparams=null, $extracontext = null) {
376 global $DB;
378 $fullname = $DB->sql_fullname();
380 $select = "deleted <> 1";
381 $params = array();
383 if (!empty($search)) {
384 $search = trim($search);
385 $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
386 " OR ". $DB->sql_like('email', ':search2', false, false).
387 " OR username = :search3)";
388 $params['search1'] = "%$search%";
389 $params['search2'] = "%$search%";
390 $params['search3'] = "$search";
393 if ($firstinitial) {
394 $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
395 $params['fni'] = "$firstinitial%";
397 if ($lastinitial) {
398 $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
399 $params['lni'] = "$lastinitial%";
402 if ($extraselect) {
403 $select .= " AND $extraselect";
404 $params = $params + (array)$extraparams;
407 if ($sort) {
408 $sort = " ORDER BY $sort $dir";
411 // If a context is specified, get extra user fields that the current user
412 // is supposed to see.
413 $extrafields = '';
414 if ($extracontext) {
415 $extrafields = get_extra_user_fields_sql($extracontext, '', '',
416 array('id', 'username', 'email', 'firstname', 'lastname', 'city', 'country',
417 'lastaccess', 'confirmed', 'mnethostid'));
420 // warning: will return UNCONFIRMED USERS
421 return $DB->get_records_sql("SELECT id, username, email, firstname, lastname, city, country,
422 lastaccess, confirmed, mnethostid, suspended $extrafields
423 FROM {user}
424 WHERE $select
425 $sort", $params, $page, $recordsperpage);
431 * Full list of users that have confirmed their accounts.
433 * @global object
434 * @return array of unconfirmed users
436 function get_users_confirmed() {
437 global $DB, $CFG;
438 return $DB->get_records_sql("SELECT *
439 FROM {user}
440 WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
444 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
448 * Returns $course object of the top-level site.
450 * @return object A {@link $COURSE} object for the site, exception if not found
452 function get_site() {
453 global $SITE, $DB;
455 if (!empty($SITE->id)) { // We already have a global to use, so return that
456 return $SITE;
459 if ($course = $DB->get_record('course', array('category'=>0))) {
460 return $course;
461 } else {
462 // course table exists, but the site is not there,
463 // unfortunately there is no automatic way to recover
464 throw new moodle_exception('nosite', 'error');
469 * Returns list of courses, for whole site, or category
471 * Returns list of courses, for whole site, or category
472 * Important: Using c.* for fields is extremely expensive because
473 * we are using distinct. You almost _NEVER_ need all the fields
474 * in such a large SELECT
476 * @global object
477 * @global object
478 * @global object
479 * @uses CONTEXT_COURSE
480 * @param string|int $categoryid Either a category id or 'all' for everything
481 * @param string $sort A field and direction to sort by
482 * @param string $fields The additional fields to return
483 * @return array Array of courses
485 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
487 global $USER, $CFG, $DB;
489 $params = array();
491 if ($categoryid !== "all" && is_numeric($categoryid)) {
492 $categoryselect = "WHERE c.category = :catid";
493 $params['catid'] = $categoryid;
494 } else {
495 $categoryselect = "";
498 if (empty($sort)) {
499 $sortstatement = "";
500 } else {
501 $sortstatement = "ORDER BY $sort";
504 $visiblecourses = array();
506 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
508 $sql = "SELECT $fields $ccselect
509 FROM {course} c
510 $ccjoin
511 $categoryselect
512 $sortstatement";
514 // pull out all course matching the cat
515 if ($courses = $DB->get_records_sql($sql, $params)) {
517 // loop throught them
518 foreach ($courses as $course) {
519 context_instance_preload($course);
520 if (isset($course->visible) && $course->visible <= 0) {
521 // for hidden courses, require visibility check
522 if (has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
523 $visiblecourses [$course->id] = $course;
525 } else {
526 $visiblecourses [$course->id] = $course;
530 return $visiblecourses;
535 * Returns list of courses, for whole site, or category
537 * Similar to get_courses, but allows paging
538 * Important: Using c.* for fields is extremely expensive because
539 * we are using distinct. You almost _NEVER_ need all the fields
540 * in such a large SELECT
542 * @global object
543 * @global object
544 * @global object
545 * @uses CONTEXT_COURSE
546 * @param string|int $categoryid Either a category id or 'all' for everything
547 * @param string $sort A field and direction to sort by
548 * @param string $fields The additional fields to return
549 * @param int $totalcount Reference for the number of courses
550 * @param string $limitfrom The course to start from
551 * @param string $limitnum The number of courses to limit to
552 * @return array Array of courses
554 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
555 &$totalcount, $limitfrom="", $limitnum="") {
556 global $USER, $CFG, $DB;
558 $params = array();
560 $categoryselect = "";
561 if ($categoryid != "all" && is_numeric($categoryid)) {
562 $categoryselect = "WHERE c.category = :catid";
563 $params['catid'] = $categoryid;
564 } else {
565 $categoryselect = "";
568 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
570 $totalcount = 0;
571 if (!$limitfrom) {
572 $limitfrom = 0;
574 $visiblecourses = array();
576 $sql = "SELECT $fields $ccselect
577 FROM {course} c
578 $ccjoin
579 $categoryselect
580 ORDER BY $sort";
582 // pull out all course matching the cat
583 $rs = $DB->get_recordset_sql($sql, $params);
584 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
585 foreach($rs as $course) {
586 context_instance_preload($course);
587 if ($course->visible <= 0) {
588 // for hidden courses, require visibility check
589 if (has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
590 $totalcount++;
591 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
592 $visiblecourses [$course->id] = $course;
595 } else {
596 $totalcount++;
597 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
598 $visiblecourses [$course->id] = $course;
602 $rs->close();
603 return $visiblecourses;
607 * Retrieve course records with the course managers and other related records
608 * that we need for print_course(). This allows print_courses() to do its job
609 * in a constant number of DB queries, regardless of the number of courses,
610 * role assignments, etc.
612 * The returned array is indexed on c.id, and each course will have
613 * - $course->managers - array containing RA objects that include a $user obj
614 * with the minimal fields needed for fullname()
616 * @global object
617 * @global object
618 * @global object
619 * @uses CONTEXT_COURSE
620 * @uses CONTEXT_SYSTEM
621 * @uses CONTEXT_COURSECAT
622 * @uses SITEID
623 * @param int|string $categoryid Either the categoryid for the courses or 'all'
624 * @param string $sort A SQL sort field and direction
625 * @param array $fields An array of additional fields to fetch
626 * @return array
628 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
630 * The plan is to
632 * - Grab the courses JOINed w/context
634 * - Grab the interesting course-manager RAs
635 * JOINed with a base user obj and add them to each course
637 * So as to do all the work in 2 DB queries. The RA+user JOIN
638 * ends up being pretty expensive if it happens over _all_
639 * courses on a large site. (Are we surprised!?)
641 * So this should _never_ get called with 'all' on a large site.
644 global $USER, $CFG, $DB;
646 $params = array();
647 $allcats = false; // bool flag
648 if ($categoryid === 'all') {
649 $categoryclause = '';
650 $allcats = true;
651 } elseif (is_numeric($categoryid)) {
652 $categoryclause = "c.category = :catid";
653 $params['catid'] = $categoryid;
654 } else {
655 debugging("Could not recognise categoryid = $categoryid");
656 $categoryclause = '';
659 $basefields = array('id', 'category', 'sortorder',
660 'shortname', 'fullname', 'idnumber',
661 'startdate', 'visible',
662 'newsitems', 'groupmode', 'groupmodeforce');
664 if (!is_null($fields) && is_string($fields)) {
665 if (empty($fields)) {
666 $fields = $basefields;
667 } else {
668 // turn the fields from a string to an array that
669 // get_user_courses_bycap() will like...
670 $fields = explode(',',$fields);
671 $fields = array_map('trim', $fields);
672 $fields = array_unique(array_merge($basefields, $fields));
674 } elseif (is_array($fields)) {
675 $fields = array_merge($basefields,$fields);
677 $coursefields = 'c.' .join(',c.', $fields);
679 if (empty($sort)) {
680 $sortstatement = "";
681 } else {
682 $sortstatement = "ORDER BY $sort";
685 $where = 'WHERE c.id != ' . SITEID;
686 if ($categoryclause !== ''){
687 $where = "$where AND $categoryclause";
690 // pull out all courses matching the cat
691 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
692 $sql = "SELECT $coursefields $ccselect
693 FROM {course} c
694 $ccjoin
695 $where
696 $sortstatement";
698 $catpaths = array();
699 $catpath = NULL;
700 if ($courses = $DB->get_records_sql($sql, $params)) {
701 // loop on courses materialising
702 // the context, and prepping data to fetch the
703 // managers efficiently later...
704 foreach ($courses as $k => $course) {
705 context_instance_preload($course);
706 $coursecontext = context_course::instance($course->id);
707 $courses[$k] = $course;
708 $courses[$k]->managers = array();
709 if ($allcats === false) {
710 // single cat, so take just the first one...
711 if ($catpath === NULL) {
712 $catpath = preg_replace(':/\d+$:', '', $coursecontext->path);
714 } else {
715 // chop off the contextid of the course itself
716 // like dirname() does...
717 $catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path);
720 } else {
721 return array(); // no courses!
724 $CFG->coursecontact = trim($CFG->coursecontact);
725 if (empty($CFG->coursecontact)) {
726 return $courses;
729 $managerroles = explode(',', $CFG->coursecontact);
730 $catctxids = '';
731 if (count($managerroles)) {
732 if ($allcats === true) {
733 $catpaths = array_unique($catpaths);
734 $ctxids = array();
735 foreach ($catpaths as $cpath) {
736 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
738 $ctxids = array_unique($ctxids);
739 $catctxids = implode( ',' , $ctxids);
740 unset($catpaths);
741 unset($cpath);
742 } else {
743 // take the ctx path from the first course
744 // as all categories will be the same...
745 $catpath = substr($catpath,1);
746 $catpath = preg_replace(':/\d+$:','',$catpath);
747 $catctxids = str_replace('/',',',$catpath);
749 if ($categoryclause !== '') {
750 $categoryclause = "AND $categoryclause";
753 * Note: Here we use a LEFT OUTER JOIN that can
754 * "optionally" match to avoid passing a ton of context
755 * ids in an IN() clause. Perhaps a subselect is faster.
757 * In any case, this SQL is not-so-nice over large sets of
758 * courses with no $categoryclause.
761 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
762 r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,
763 rn.name AS rolecoursealias, u.id AS userid, u.firstname, u.lastname
764 FROM {role_assignments} ra
765 JOIN {context} ctx ON ra.contextid = ctx.id
766 JOIN {user} u ON ra.userid = u.id
767 JOIN {role} r ON ra.roleid = r.id
768 LEFT JOIN {role_names} rn ON (rn.contextid = ctx.id AND rn.roleid = r.id)
769 LEFT OUTER JOIN {course} c
770 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
771 WHERE ( c.id IS NOT NULL";
772 // under certain conditions, $catctxids is NULL
773 if($catctxids == NULL){
774 $sql .= ") ";
775 }else{
776 $sql .= " OR ra.contextid IN ($catctxids) )";
779 $sql .= "AND ra.roleid IN ({$CFG->coursecontact})
780 $categoryclause
781 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
782 $rs = $DB->get_recordset_sql($sql, $params);
784 // This loop is fairly stupid as it stands - might get better
785 // results doing an initial pass clustering RAs by path.
786 foreach($rs as $ra) {
787 $user = new stdClass;
788 $user->id = $ra->userid; unset($ra->userid);
789 $user->firstname = $ra->firstname; unset($ra->firstname);
790 $user->lastname = $ra->lastname; unset($ra->lastname);
791 $ra->user = $user;
792 if ($ra->contextlevel == CONTEXT_SYSTEM) {
793 foreach ($courses as $k => $course) {
794 $courses[$k]->managers[] = $ra;
796 } else if ($ra->contextlevel == CONTEXT_COURSECAT) {
797 if ($allcats === false) {
798 // It always applies
799 foreach ($courses as $k => $course) {
800 $courses[$k]->managers[] = $ra;
802 } else {
803 foreach ($courses as $k => $course) {
804 $coursecontext = context_course::instance($course->id);
805 // Note that strpos() returns 0 as "matched at pos 0"
806 if (strpos($coursecontext->path, $ra->path.'/') === 0) {
807 // Only add it to subpaths
808 $courses[$k]->managers[] = $ra;
812 } else { // course-level
813 if (!array_key_exists($ra->instanceid, $courses)) {
814 //this course is not in a list, probably a frontpage course
815 continue;
817 $courses[$ra->instanceid]->managers[] = $ra;
820 $rs->close();
823 return $courses;
827 * A list of courses that match a search
829 * @global object
830 * @global object
831 * @param array $searchterms An array of search criteria
832 * @param string $sort A field and direction to sort by
833 * @param int $page The page number to get
834 * @param int $recordsperpage The number of records per page
835 * @param int $totalcount Passed in by reference.
836 * @return object {@link $COURSE} records
838 function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
839 global $CFG, $DB;
841 if ($DB->sql_regex_supported()) {
842 $REGEXP = $DB->sql_regex(true);
843 $NOTREGEXP = $DB->sql_regex(false);
846 $searchcond = array();
847 $params = array();
848 $i = 0;
850 // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
851 if ($DB->get_dbfamily() == 'oracle') {
852 $concat = $DB->sql_concat('c.summary', "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
853 } else {
854 $concat = $DB->sql_concat("COALESCE(c.summary, '". $DB->sql_empty() ."')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
857 foreach ($searchterms as $searchterm) {
858 $i++;
860 $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
861 /// will use it to simulate the "-" operator with LIKE clause
863 /// Under Oracle and MSSQL, trim the + and - operators and perform
864 /// simpler LIKE (or NOT LIKE) queries
865 if (!$DB->sql_regex_supported()) {
866 if (substr($searchterm, 0, 1) == '-') {
867 $NOT = true;
869 $searchterm = trim($searchterm, '+-');
872 // TODO: +- may not work for non latin languages
874 if (substr($searchterm,0,1) == '+') {
875 $searchterm = trim($searchterm, '+-');
876 $searchterm = preg_quote($searchterm, '|');
877 $searchcond[] = "$concat $REGEXP :ss$i";
878 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
880 } else if (substr($searchterm,0,1) == "-") {
881 $searchterm = trim($searchterm, '+-');
882 $searchterm = preg_quote($searchterm, '|');
883 $searchcond[] = "$concat $NOTREGEXP :ss$i";
884 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
886 } else {
887 $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
888 $params['ss'.$i] = "%$searchterm%";
892 if (empty($searchcond)) {
893 $totalcount = 0;
894 return array();
897 $searchcond = implode(" AND ", $searchcond);
899 $courses = array();
900 $c = 0; // counts how many visible courses we've seen
902 // Tiki pagination
903 $limitfrom = $page * $recordsperpage;
904 $limitto = $limitfrom + $recordsperpage;
906 list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
907 $sql = "SELECT c.* $ccselect
908 FROM {course} c
909 $ccjoin
910 WHERE $searchcond AND c.id <> ".SITEID."
911 ORDER BY $sort";
913 $rs = $DB->get_recordset_sql($sql, $params);
914 foreach($rs as $course) {
915 context_instance_preload($course);
916 $coursecontext = context_course::instance($course->id);
917 if ($course->visible || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
918 // Don't exit this loop till the end
919 // we need to count all the visible courses
920 // to update $totalcount
921 if ($c >= $limitfrom && $c < $limitto) {
922 $courses[$course->id] = $course;
924 $c++;
927 $rs->close();
929 // our caller expects 2 bits of data - our return
930 // array, and an updated $totalcount
931 $totalcount = $c;
932 return $courses;
937 * Returns a sorted list of categories. Each category object has a context
938 * property that is a context object.
940 * When asking for $parent='none' it will return all the categories, regardless
941 * of depth. Wheen asking for a specific parent, the default is to return
942 * a "shallow" resultset. Pass false to $shallow and it will return all
943 * the child categories as well.
945 * @global object
946 * @uses CONTEXT_COURSECAT
947 * @param string $parent The parent category if any
948 * @param string $sort the sortorder
949 * @param bool $shallow - set to false to get the children too
950 * @return array of categories
952 function get_categories($parent='none', $sort=NULL, $shallow=true) {
953 global $DB;
955 if ($sort === NULL) {
956 $sort = 'ORDER BY cc.sortorder ASC';
957 } elseif ($sort ==='') {
958 // leave it as empty
959 } else {
960 $sort = "ORDER BY $sort";
963 list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
965 if ($parent === 'none') {
966 $sql = "SELECT cc.* $ccselect
967 FROM {course_categories} cc
968 $ccjoin
969 $sort";
970 $params = array();
972 } elseif ($shallow) {
973 $sql = "SELECT cc.* $ccselect
974 FROM {course_categories} cc
975 $ccjoin
976 WHERE cc.parent=?
977 $sort";
978 $params = array($parent);
980 } else {
981 $sql = "SELECT cc.* $ccselect
982 FROM {course_categories} cc
983 $ccjoin
984 JOIN {course_categories} ccp
985 ON ((cc.parent = ccp.id) OR (cc.path LIKE ".$DB->sql_concat('ccp.path',"'/%'")."))
986 WHERE ccp.id=?
987 $sort";
988 $params = array($parent);
990 $categories = array();
992 $rs = $DB->get_recordset_sql($sql, $params);
993 foreach($rs as $cat) {
994 context_instance_preload($cat);
995 $catcontext = context_coursecat::instance($cat->id);
996 if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) {
997 $categories[$cat->id] = $cat;
1000 $rs->close();
1001 return $categories;
1006 * Returns an array of category ids of all the subcategories for a given
1007 * category.
1009 * @global object
1010 * @param int $catid - The id of the category whose subcategories we want to find.
1011 * @return array of category ids.
1013 function get_all_subcategories($catid) {
1014 global $DB;
1016 $subcats = array();
1018 if ($categories = $DB->get_records('course_categories', array('parent'=>$catid))) {
1019 foreach ($categories as $cat) {
1020 array_push($subcats, $cat->id);
1021 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
1024 return $subcats;
1028 * Return specified category, default if given does not exist
1030 * @global object
1031 * @uses MAX_COURSES_IN_CATEGORY
1032 * @uses CONTEXT_COURSECAT
1033 * @uses SYSCONTEXTID
1034 * @param int $catid course category id
1035 * @return object caregory
1037 function get_course_category($catid=0) {
1038 global $DB;
1040 $category = false;
1042 if (!empty($catid)) {
1043 $category = $DB->get_record('course_categories', array('id'=>$catid));
1046 if (!$category) {
1047 // the first category is considered default for now
1048 if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
1049 $category = reset($category);
1051 } else {
1052 $cat = new stdClass();
1053 $cat->name = get_string('miscellaneous');
1054 $cat->depth = 1;
1055 $cat->sortorder = MAX_COURSES_IN_CATEGORY;
1056 $cat->timemodified = time();
1057 $catid = $DB->insert_record('course_categories', $cat);
1058 // make sure category context exists
1059 context_coursecat::instance($catid);
1060 mark_context_dirty('/'.SYSCONTEXTID);
1061 fix_course_sortorder(); // Required to build course_categories.depth and .path.
1062 $category = $DB->get_record('course_categories', array('id'=>$catid));
1066 return $category;
1070 * Fixes course category and course sortorder, also verifies category and course parents and paths.
1071 * (circular references are not fixed)
1073 * @global object
1074 * @global object
1075 * @uses MAX_COURSES_IN_CATEGORY
1076 * @uses MAX_COURSE_CATEGORIES
1077 * @uses SITEID
1078 * @uses CONTEXT_COURSE
1079 * @return void
1081 function fix_course_sortorder() {
1082 global $DB, $SITE;
1084 //WARNING: this is PHP5 only code!
1086 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
1087 //move all categories that are not sorted yet to the end
1088 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
1091 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
1092 $topcats = array();
1093 $brokencats = array();
1094 foreach ($allcats as $cat) {
1095 $sortorder = (int)$cat->sortorder;
1096 if (!$cat->parent) {
1097 while(isset($topcats[$sortorder])) {
1098 $sortorder++;
1100 $topcats[$sortorder] = $cat;
1101 continue;
1103 if (!isset($allcats[$cat->parent])) {
1104 $brokencats[] = $cat;
1105 continue;
1107 if (!isset($allcats[$cat->parent]->children)) {
1108 $allcats[$cat->parent]->children = array();
1110 while(isset($allcats[$cat->parent]->children[$sortorder])) {
1111 $sortorder++;
1113 $allcats[$cat->parent]->children[$sortorder] = $cat;
1115 unset($allcats);
1117 // add broken cats to category tree
1118 if ($brokencats) {
1119 $defaultcat = reset($topcats);
1120 foreach ($brokencats as $cat) {
1121 $topcats[] = $cat;
1125 // now walk recursively the tree and fix any problems found
1126 $sortorder = 0;
1127 $fixcontexts = array();
1128 _fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts);
1130 // detect if there are "multiple" frontpage courses and fix them if needed
1131 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
1132 if (count($frontcourses) > 1) {
1133 if (isset($frontcourses[SITEID])) {
1134 $frontcourse = $frontcourses[SITEID];
1135 unset($frontcourses[SITEID]);
1136 } else {
1137 $frontcourse = array_shift($frontcourses);
1139 $defaultcat = reset($topcats);
1140 foreach ($frontcourses as $course) {
1141 $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
1142 $context = context_course::instance($course->id);
1143 $fixcontexts[$context->id] = $context;
1145 unset($frontcourses);
1146 } else {
1147 $frontcourse = reset($frontcourses);
1150 // now fix the paths and depths in context table if needed
1151 if ($fixcontexts) {
1152 foreach ($fixcontexts as $fixcontext) {
1153 $fixcontext->reset_paths(false);
1155 context_helper::build_all_paths(false);
1156 unset($fixcontexts);
1159 // release memory
1160 unset($topcats);
1161 unset($brokencats);
1162 unset($fixcontexts);
1164 // fix frontpage course sortorder
1165 if ($frontcourse->sortorder != 1) {
1166 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
1169 // now fix the course counts in category records if needed
1170 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
1171 FROM {course_categories} cc
1172 LEFT JOIN {course} c ON c.category = cc.id
1173 GROUP BY cc.id, cc.coursecount
1174 HAVING cc.coursecount <> COUNT(c.id)";
1176 if ($updatecounts = $DB->get_records_sql($sql)) {
1177 // categories with more courses than MAX_COURSES_IN_CATEGORY
1178 $categories = array();
1179 foreach ($updatecounts as $cat) {
1180 $cat->coursecount = $cat->newcount;
1181 if ($cat->coursecount >= MAX_COURSES_IN_CATEGORY) {
1182 $categories[] = $cat->id;
1184 unset($cat->newcount);
1185 $DB->update_record_raw('course_categories', $cat, true);
1187 if (!empty($categories)) {
1188 $str = implode(', ', $categories);
1189 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);
1193 // now make sure that sortorders in course table are withing the category sortorder ranges
1194 $sql = "SELECT DISTINCT cc.id, cc.sortorder
1195 FROM {course_categories} cc
1196 JOIN {course} c ON c.category = cc.id
1197 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
1199 if ($fixcategories = $DB->get_records_sql($sql)) {
1200 //fix the course sortorder ranges
1201 foreach ($fixcategories as $cat) {
1202 $sql = "UPDATE {course}
1203 SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
1204 WHERE category = ?";
1205 $DB->execute($sql, array($cat->sortorder, $cat->id));
1208 unset($fixcategories);
1210 // categories having courses with sortorder duplicates or having gaps in sortorder
1211 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
1212 FROM {course} c1
1213 JOIN {course} c2 ON c1.sortorder = c2.sortorder
1214 JOIN {course_categories} cc ON (c1.category = cc.id)
1215 WHERE c1.id <> c2.id";
1216 $fixcategories = $DB->get_records_sql($sql);
1218 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
1219 FROM {course_categories} cc
1220 JOIN {course} c ON c.category = cc.id
1221 GROUP BY cc.id, cc.sortorder, cc.coursecount
1222 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
1223 $gapcategories = $DB->get_records_sql($sql);
1225 foreach ($gapcategories as $cat) {
1226 if (isset($fixcategories[$cat->id])) {
1227 // duplicates detected already
1229 } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
1230 // easy - new course inserted with sortorder 0, the rest is ok
1231 $sql = "UPDATE {course}
1232 SET sortorder = sortorder + 1
1233 WHERE category = ?";
1234 $DB->execute($sql, array($cat->id));
1236 } else {
1237 // it needs full resorting
1238 $fixcategories[$cat->id] = $cat;
1241 unset($gapcategories);
1243 // fix course sortorders in problematic categories only
1244 foreach ($fixcategories as $cat) {
1245 $i = 1;
1246 $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1247 foreach ($courses as $course) {
1248 if ($course->sortorder != $cat->sortorder + $i) {
1249 $course->sortorder = $cat->sortorder + $i;
1250 $DB->update_record_raw('course', $course, true);
1252 $i++;
1258 * Internal recursive category verification function, do not use directly!
1260 * @todo Document the arguments of this function better
1262 * @global object
1263 * @uses MAX_COURSES_IN_CATEGORY
1264 * @uses CONTEXT_COURSECAT
1265 * @param array $children
1266 * @param int $sortorder
1267 * @param string $parent
1268 * @param int $depth
1269 * @param string $path
1270 * @param array $fixcontexts
1271 * @return void
1273 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1274 global $DB;
1276 $depth++;
1278 foreach ($children as $cat) {
1279 $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1280 $update = false;
1281 if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1282 $cat->parent = $parent;
1283 $cat->depth = $depth;
1284 $cat->path = $path.'/'.$cat->id;
1285 $update = true;
1287 // make sure context caches are rebuild and dirty contexts marked
1288 $context = context_coursecat::instance($cat->id);
1289 $fixcontexts[$context->id] = $context;
1291 if ($cat->sortorder != $sortorder) {
1292 $cat->sortorder = $sortorder;
1293 $update = true;
1295 if ($update) {
1296 $DB->update_record('course_categories', $cat, true);
1298 if (isset($cat->children)) {
1299 _fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts);
1305 * List of remote courses that a user has access to via MNET.
1306 * Works only on the IDP
1308 * @global object
1309 * @global object
1310 * @param int @userid The user id to get remote courses for
1311 * @return array Array of {@link $COURSE} of course objects
1313 function get_my_remotecourses($userid=0) {
1314 global $DB, $USER;
1316 if (empty($userid)) {
1317 $userid = $USER->id;
1320 // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1321 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1322 c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1323 h.name AS hostname
1324 FROM {mnetservice_enrol_courses} c
1325 JOIN (SELECT DISTINCT hostid, remotecourseid
1326 FROM {mnetservice_enrol_enrolments}
1327 WHERE userid = ?
1328 ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1329 JOIN {mnet_host} h ON h.id = c.hostid";
1331 return $DB->get_records_sql($sql, array($userid));
1335 * List of remote hosts that a user has access to via MNET.
1336 * Works on the SP
1338 * @global object
1339 * @global object
1340 * @return array|bool Array of host objects or false
1342 function get_my_remotehosts() {
1343 global $CFG, $USER;
1345 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1346 return false; // Return nothing on the IDP
1348 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1349 return $USER->mnet_foreign_host_array;
1351 return false;
1355 * This function creates a default separated/connected scale
1357 * This function creates a default separated/connected scale
1358 * so there's something in the database. The locations of
1359 * strings and files is a bit odd, but this is because we
1360 * need to maintain backward compatibility with many different
1361 * existing language translations and older sites.
1363 * @global object
1364 * @return void
1366 function make_default_scale() {
1367 global $DB;
1369 $defaultscale = new stdClass();
1370 $defaultscale->courseid = 0;
1371 $defaultscale->userid = 0;
1372 $defaultscale->name = get_string('separateandconnected');
1373 $defaultscale->description = get_string('separateandconnectedinfo');
1374 $defaultscale->scale = get_string('postrating1', 'forum').','.
1375 get_string('postrating2', 'forum').','.
1376 get_string('postrating3', 'forum');
1377 $defaultscale->timemodified = time();
1379 $defaultscale->id = $DB->insert_record('scale', $defaultscale);
1380 $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id));
1385 * Returns a menu of all available scales from the site as well as the given course
1387 * @global object
1388 * @param int $courseid The id of the course as found in the 'course' table.
1389 * @return array
1391 function get_scales_menu($courseid=0) {
1392 global $DB;
1394 $sql = "SELECT id, name
1395 FROM {scale}
1396 WHERE courseid = 0 or courseid = ?
1397 ORDER BY courseid ASC, name ASC";
1398 $params = array($courseid);
1400 if ($scales = $DB->get_records_sql_menu($sql, $params)) {
1401 return $scales;
1404 make_default_scale();
1406 return $DB->get_records_sql_menu($sql, $params);
1412 * Given a set of timezone records, put them in the database, replacing what is there
1414 * @global object
1415 * @param array $timezones An array of timezone records
1416 * @return void
1418 function update_timezone_records($timezones) {
1419 global $DB;
1421 /// Clear out all the old stuff
1422 $DB->delete_records('timezone');
1424 /// Insert all the new stuff
1425 foreach ($timezones as $timezone) {
1426 if (is_array($timezone)) {
1427 $timezone = (object)$timezone;
1429 $DB->insert_record('timezone', $timezone);
1434 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1437 * Just gets a raw list of all modules in a course
1439 * @global object
1440 * @param int $courseid The id of the course as found in the 'course' table.
1441 * @return array
1443 function get_course_mods($courseid) {
1444 global $DB;
1446 if (empty($courseid)) {
1447 return false; // avoid warnings
1450 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1451 FROM {modules} m, {course_modules} cm
1452 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1453 array($courseid)); // no disabled mods
1458 * Given an id of a course module, finds the coursemodule description
1460 * @global object
1461 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1462 * @param int $cmid course module id (id in course_modules table)
1463 * @param int $courseid optional course id for extra validation
1464 * @param bool $sectionnum include relative section number (0,1,2 ...)
1465 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1466 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1467 * MUST_EXIST means throw exception if no record or multiple records found
1468 * @return stdClass
1470 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1471 global $DB;
1473 $params = array('cmid'=>$cmid);
1475 if (!$modulename) {
1476 if (!$modulename = $DB->get_field_sql("SELECT md.name
1477 FROM {modules} md
1478 JOIN {course_modules} cm ON cm.module = md.id
1479 WHERE cm.id = :cmid", $params, $strictness)) {
1480 return false;
1484 $params['modulename'] = $modulename;
1486 $courseselect = "";
1487 $sectionfield = "";
1488 $sectionjoin = "";
1490 if ($courseid) {
1491 $courseselect = "AND cm.course = :courseid";
1492 $params['courseid'] = $courseid;
1495 if ($sectionnum) {
1496 $sectionfield = ", cw.section AS sectionnum";
1497 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1500 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1501 FROM {course_modules} cm
1502 JOIN {modules} md ON md.id = cm.module
1503 JOIN {".$modulename."} m ON m.id = cm.instance
1504 $sectionjoin
1505 WHERE cm.id = :cmid AND md.name = :modulename
1506 $courseselect";
1508 return $DB->get_record_sql($sql, $params, $strictness);
1512 * Given an instance number of a module, finds the coursemodule description
1514 * @global object
1515 * @param string $modulename name of module type, eg. resource, assignment,...
1516 * @param int $instance module instance number (id in resource, assignment etc. table)
1517 * @param int $courseid optional course id for extra validation
1518 * @param bool $sectionnum include relative section number (0,1,2 ...)
1519 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1520 * IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1521 * MUST_EXIST means throw exception if no record or multiple records found
1522 * @return stdClass
1524 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1525 global $DB;
1527 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1529 $courseselect = "";
1530 $sectionfield = "";
1531 $sectionjoin = "";
1533 if ($courseid) {
1534 $courseselect = "AND cm.course = :courseid";
1535 $params['courseid'] = $courseid;
1538 if ($sectionnum) {
1539 $sectionfield = ", cw.section AS sectionnum";
1540 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1543 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1544 FROM {course_modules} cm
1545 JOIN {modules} md ON md.id = cm.module
1546 JOIN {".$modulename."} m ON m.id = cm.instance
1547 $sectionjoin
1548 WHERE m.id = :instance AND md.name = :modulename
1549 $courseselect";
1551 return $DB->get_record_sql($sql, $params, $strictness);
1555 * Returns all course modules of given activity in course
1557 * @param string $modulename The module name (forum, quiz, etc.)
1558 * @param int $courseid The course id to get modules for
1559 * @param string $extrafields extra fields starting with m.
1560 * @return array Array of results
1562 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1563 global $DB;
1565 if (!empty($extrafields)) {
1566 $extrafields = ", $extrafields";
1568 $params = array();
1569 $params['courseid'] = $courseid;
1570 $params['modulename'] = $modulename;
1573 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1574 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1575 WHERE cm.course = :courseid AND
1576 cm.instance = m.id AND
1577 md.name = :modulename AND
1578 md.id = cm.module", $params);
1582 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1584 * Returns an array of all the active instances of a particular
1585 * module in given courses, sorted in the order they are defined
1586 * in the course. Returns an empty array on any errors.
1588 * The returned objects includle the columns cw.section, cm.visible,
1589 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1591 * @global object
1592 * @global object
1593 * @param string $modulename The name of the module to get instances for
1594 * @param array $courses an array of course objects.
1595 * @param int $userid
1596 * @param int $includeinvisible
1597 * @return array of module instance objects, including some extra fields from the course_modules
1598 * and course_sections tables, or an empty array if an error occurred.
1600 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1601 global $CFG, $DB;
1603 $outputarray = array();
1605 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1606 return $outputarray;
1609 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1610 $params['modulename'] = $modulename;
1612 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1613 cm.groupmode, cm.groupingid, cm.groupmembersonly
1614 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1615 {".$modulename."} m
1616 WHERE cm.course $coursessql AND
1617 cm.instance = m.id AND
1618 cm.section = cw.id AND
1619 md.name = :modulename AND
1620 md.id = cm.module", $params)) {
1621 return $outputarray;
1624 foreach ($courses as $course) {
1625 $modinfo = get_fast_modinfo($course, $userid);
1627 if (empty($modinfo->instances[$modulename])) {
1628 continue;
1631 foreach ($modinfo->instances[$modulename] as $cm) {
1632 if (!$includeinvisible and !$cm->uservisible) {
1633 continue;
1635 if (!isset($rawmods[$cm->id])) {
1636 continue;
1638 $instance = $rawmods[$cm->id];
1639 if (!empty($cm->extra)) {
1640 $instance->extra = $cm->extra;
1642 $outputarray[] = $instance;
1646 return $outputarray;
1650 * Returns an array of all the active instances of a particular module in a given course,
1651 * sorted in the order they are defined.
1653 * Returns an array of all the active instances of a particular
1654 * module in a given course, sorted in the order they are defined
1655 * in the course. Returns an empty array on any errors.
1657 * The returned objects includle the columns cw.section, cm.visible,
1658 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1660 * Simply calls {@link all_instances_in_courses()} with a single provided course
1662 * @param string $modulename The name of the module to get instances for
1663 * @param object $course The course obect.
1664 * @return array of module instance objects, including some extra fields from the course_modules
1665 * and course_sections tables, or an empty array if an error occurred.
1666 * @param int $userid
1667 * @param int $includeinvisible
1669 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1670 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1675 * Determine whether a module instance is visible within a course
1677 * Given a valid module object with info about the id and course,
1678 * and the module's type (eg "forum") returns whether the object
1679 * is visible or not, groupmembersonly visibility not tested
1681 * @global object
1683 * @param $moduletype Name of the module eg 'forum'
1684 * @param $module Object which is the instance of the module
1685 * @return bool Success
1687 function instance_is_visible($moduletype, $module) {
1688 global $DB;
1690 if (!empty($module->id)) {
1691 $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1692 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1693 FROM {course_modules} cm, {modules} m
1694 WHERE cm.course = :courseid AND
1695 cm.module = m.id AND
1696 m.name = :moduletype AND
1697 cm.instance = :moduleid", $params)) {
1699 foreach ($records as $record) { // there should only be one - use the first one
1700 return $record->visible;
1704 return true; // visible by default!
1708 * Determine whether a course module is visible within a course,
1709 * this is different from instance_is_visible() - faster and visibility for user
1711 * @global object
1712 * @global object
1713 * @uses DEBUG_DEVELOPER
1714 * @uses CONTEXT_MODULE
1715 * @uses CONDITION_MISSING_EXTRATABLE
1716 * @param object $cm object
1717 * @param int $userid empty means current user
1718 * @return bool Success
1720 function coursemodule_visible_for_user($cm, $userid=0) {
1721 global $USER,$CFG;
1723 if (empty($cm->id)) {
1724 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1725 return false;
1727 if (empty($userid)) {
1728 $userid = $USER->id;
1730 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', context_module::instance($cm->id), $userid)) {
1731 return false;
1733 if ($CFG->enableavailability) {
1734 require_once($CFG->libdir.'/conditionlib.php');
1735 $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE);
1736 if(!$ci->is_available($cm->availableinfo,false,$userid) and
1737 !has_capability('moodle/course:viewhiddenactivities',
1738 context_module::instance($cm->id), $userid)) {
1739 return false;
1742 return groups_course_module_visible($cm, $userid);
1748 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1752 * Add an entry to the log table.
1754 * Add an entry to the log table. These are "action" focussed rather
1755 * than web server hits, and provide a way to easily reconstruct what
1756 * any particular student has been doing.
1758 * @package core
1759 * @category log
1760 * @global moodle_database $DB
1761 * @global stdClass $CFG
1762 * @global stdClass $USER
1763 * @uses SITEID
1764 * @uses DEBUG_DEVELOPER
1765 * @uses DEBUG_ALL
1766 * @param int $courseid The course id
1767 * @param string $module The module name e.g. forum, journal, resource, course, user etc
1768 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1769 * @param string $url The file and parameters used to see the results of the action
1770 * @param string $info Additional description information
1771 * @param string $cm The course_module->id if there is one
1772 * @param string $user If log regards $user other than $USER
1773 * @return void
1775 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1776 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1777 // This is for a good reason: it is the most frequently used DB update function,
1778 // so it has been optimised for speed.
1779 global $DB, $CFG, $USER;
1781 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
1782 $cm = 0;
1785 if ($user) {
1786 $userid = $user;
1787 } else {
1788 if (session_is_loggedinas()) { // Don't log
1789 return;
1791 $userid = empty($USER->id) ? '0' : $USER->id;
1794 if (isset($CFG->logguests) and !$CFG->logguests) {
1795 if (!$userid or isguestuser($userid)) {
1796 return;
1800 $REMOTE_ADDR = getremoteaddr();
1802 $timenow = time();
1803 $info = $info;
1804 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1805 $url = html_entity_decode($url);
1806 } else {
1807 $url = '';
1810 // Restrict length of log lines to the space actually available in the
1811 // database so that it doesn't cause a DB error. Log a warning so that
1812 // developers can avoid doing things which are likely to cause this on a
1813 // routine basis.
1814 if(!empty($info) && textlib::strlen($info)>255) {
1815 $info = textlib::substr($info,0,252).'...';
1816 debugging('Warning: logged very long info',DEBUG_DEVELOPER);
1819 // If the 100 field size is changed, also need to alter print_log in course/lib.php
1820 if(!empty($url) && textlib::strlen($url)>100) {
1821 $url = textlib::substr($url,0,97).'...';
1822 debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
1825 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++;};
1827 $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
1828 'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
1830 try {
1831 $DB->insert_record_raw('log', $log, false);
1832 } catch (dml_exception $e) {
1833 debugging('Error: Could not insert a new entry to the Moodle log. '. $e->error, DEBUG_ALL);
1835 // MDL-11893, alert $CFG->supportemail if insert into log failed
1836 if ($CFG->supportemail and empty($CFG->noemailever)) {
1837 // email_to_user is not usable because email_to_user tries to write to the logs table,
1838 // and this will get caught in an infinite loop, if disk is full
1839 $site = get_site();
1840 $subject = 'Insert into log failed at your moodle site '.$site->fullname;
1841 $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";
1842 $message .= "The failed query parameters are:\n\n" . var_export($log, true);
1844 $lasttime = get_config('admin', 'lastloginserterrormail');
1845 if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
1846 //using email directly rather than messaging as they may not be able to log in to access a message
1847 mail($CFG->supportemail, $subject, $message);
1848 set_config('lastloginserterrormail', time(), 'admin');
1855 * Store user last access times - called when use enters a course or site
1857 * @package core
1858 * @category log
1859 * @global stdClass $USER
1860 * @global stdClass $CFG
1861 * @global moodle_database $DB
1862 * @uses LASTACCESS_UPDATE_SECS
1863 * @uses SITEID
1864 * @param int $courseid empty courseid means site
1865 * @return void
1867 function user_accesstime_log($courseid=0) {
1868 global $USER, $CFG, $DB;
1870 if (!isloggedin() or session_is_loggedinas()) {
1871 // no access tracking
1872 return;
1875 if (isguestuser()) {
1876 // Do not update guest access times/ips for performance.
1877 return;
1880 if (empty($courseid)) {
1881 $courseid = SITEID;
1884 $timenow = time();
1886 /// Store site lastaccess time for the current user
1887 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1888 /// Update $USER->lastaccess for next checks
1889 $USER->lastaccess = $timenow;
1891 $last = new stdClass();
1892 $last->id = $USER->id;
1893 $last->lastip = getremoteaddr();
1894 $last->lastaccess = $timenow;
1896 $DB->update_record_raw('user', $last);
1899 if ($courseid == SITEID) {
1900 /// no user_lastaccess for frontpage
1901 return;
1904 /// Store course lastaccess times for the current user
1905 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
1907 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
1909 if ($lastaccess === false) {
1910 // Update course lastaccess for next checks
1911 $USER->currentcourseaccess[$courseid] = $timenow;
1913 $last = new stdClass();
1914 $last->userid = $USER->id;
1915 $last->courseid = $courseid;
1916 $last->timeaccess = $timenow;
1917 $DB->insert_record_raw('user_lastaccess', $last, false);
1919 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
1920 // no need to update now, it was updated recently in concurrent login ;-)
1922 } else {
1923 // Update course lastaccess for next checks
1924 $USER->currentcourseaccess[$courseid] = $timenow;
1926 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
1932 * Select all log records based on SQL criteria
1934 * @package core
1935 * @category log
1936 * @global moodle_database $DB
1937 * @param string $select SQL select criteria
1938 * @param array $params named sql type params
1939 * @param string $order SQL order by clause to sort the records returned
1940 * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
1941 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
1942 * @param int $totalcount Passed in by reference.
1943 * @return array
1945 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1946 global $DB;
1948 if ($order) {
1949 $order = "ORDER BY $order";
1952 $selectsql = "";
1953 $countsql = "";
1955 if ($select) {
1956 $select = "WHERE $select";
1959 $sql = "SELECT COUNT(*)
1960 FROM {log} l
1961 $select";
1963 $totalcount = $DB->count_records_sql($sql, $params);
1965 $sql = "SELECT l.*, u.firstname, u.lastname, u.picture
1966 FROM {log} l
1967 LEFT JOIN {user} u ON l.userid = u.id
1968 $select
1969 $order";
1971 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
1976 * Select all log records for a given course and user
1978 * @package core
1979 * @category log
1980 * @global moodle_database $DB
1981 * @uses DAYSECS
1982 * @param int $userid The id of the user as found in the 'user' table.
1983 * @param int $courseid The id of the course as found in the 'course' table.
1984 * @param string $coursestart unix timestamp representing course start date and time.
1985 * @return array
1987 function get_logs_usercourse($userid, $courseid, $coursestart) {
1988 global $DB;
1990 $params = array();
1992 $courseselect = '';
1993 if ($courseid) {
1994 $courseselect = "AND course = :courseid";
1995 $params['courseid'] = $courseid;
1997 $params['userid'] = $userid;
1998 $$coursestart = (int)$coursestart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
2000 return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
2001 FROM {log}
2002 WHERE userid = :userid
2003 AND time > $coursestart $courseselect
2004 GROUP BY FLOOR((time - $coursestart)/". DAYSECS .")", $params);
2008 * Select all log records for a given course, user, and day
2010 * @package core
2011 * @category log
2012 * @global moodle_database $DB
2013 * @uses HOURSECS
2014 * @param int $userid The id of the user as found in the 'user' table.
2015 * @param int $courseid The id of the course as found in the 'course' table.
2016 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
2017 * @return array
2019 function get_logs_userday($userid, $courseid, $daystart) {
2020 global $DB;
2022 $params = array('userid'=>$userid);
2024 $courseselect = '';
2025 if ($courseid) {
2026 $courseselect = "AND course = :courseid";
2027 $params['courseid'] = $courseid;
2029 $daystart = (int)$daystart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
2031 return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
2032 FROM {log}
2033 WHERE userid = :userid
2034 AND time > $daystart $courseselect
2035 GROUP BY FLOOR((time - $daystart)/". HOURSECS .") ", $params);
2039 * Returns an object with counts of failed login attempts
2041 * Returns information about failed login attempts. If the current user is
2042 * an admin, then two numbers are returned: the number of attempts and the
2043 * number of accounts. For non-admins, only the attempts on the given user
2044 * are shown.
2046 * @global moodle_database $DB
2047 * @uses CONTEXT_SYSTEM
2048 * @param string $mode Either 'admin' or 'everybody'
2049 * @param string $username The username we are searching for
2050 * @param string $lastlogin The date from which we are searching
2051 * @return int
2053 function count_login_failures($mode, $username, $lastlogin) {
2054 global $DB;
2056 $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
2057 $select = "module='login' AND action='error' AND time > :lastlogin";
2059 $count = new stdClass();
2061 if (is_siteadmin()) {
2062 if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
2063 $count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
2064 return $count;
2066 } else if ($mode == 'everybody') {
2067 if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
2068 return $count;
2071 return NULL;
2075 /// GENERAL HELPFUL THINGS ///////////////////////////////////
2078 * Dumps a given object's information for debugging purposes
2080 * When used in a CLI script, the object's information is written to the standard
2081 * error output stream. When used in a web script, the object is dumped to a
2082 * pre-formatted block with the "notifytiny" CSS class.
2084 * @param mixed $object The data to be printed
2085 * @return void output is echo'd
2087 function print_object($object) {
2089 // we may need a lot of memory here
2090 raise_memory_limit(MEMORY_EXTRA);
2092 if (CLI_SCRIPT) {
2093 fwrite(STDERR, print_r($object, true));
2094 fwrite(STDERR, PHP_EOL);
2095 } else {
2096 echo html_writer::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
2101 * This function is the official hook inside XMLDB stuff to delegate its debug to one
2102 * external function.
2104 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
2105 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
2107 * @uses DEBUG_DEVELOPER
2108 * @param string $message string contains the error message
2109 * @param object $object object XMLDB object that fired the debug
2111 function xmldb_debug($message, $object) {
2113 debugging($message, DEBUG_DEVELOPER);
2117 * @global object
2118 * @uses CONTEXT_COURSECAT
2119 * @return boolean Whether the user can create courses in any category in the system.
2121 function user_can_create_courses() {
2122 global $DB;
2123 $catsrs = $DB->get_recordset('course_categories');
2124 foreach ($catsrs as $cat) {
2125 if (has_capability('moodle/course:create', context_coursecat::instance($cat->id))) {
2126 $catsrs->close();
2127 return true;
2130 $catsrs->close();
2131 return false;