20fab6f94480560bd24d9b1f45b98e8da775425e
[moodle.git] / lib / datalib.php
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.
13 //
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.
19  *
20  * Other main libraries:
21  * - weblib.php - functions that produce web output
22  * - moodlelib.php - general-purpose Moodle functions
23  *
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
27  */
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!
34  */
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!
40   */
41 define('MAX_COURSE_CATEGORIES', 10000);
43 /**
44  * Number of seconds to wait before updating lastaccess information in DB.
45  */
46 define('LASTACCESS_UPDATE_SECS', 60);
48 /**
49  * Returns $user object of the main admin user
50  *
51  * @static stdClass $mainadmin
52  * @return stdClass {@link $USER} record from DB, false if not found
53  */
54 function get_admin() {
55     global $CFG, $DB;
57     static $mainadmin = null;
58     static $prevadmins = null;
60     if (empty($CFG->siteadmins)) {
61         // Should not happen on an ordinary site.
62         // It does however happen during unit tests.
63         return false;
64     }
66     if (isset($mainadmin) and $prevadmins === $CFG->siteadmins) {
67         return clone($mainadmin);
68     }
70     $mainadmin = null;
72     foreach (explode(',', $CFG->siteadmins) as $id) {
73         if ($user = $DB->get_record('user', array('id'=>$id, 'deleted'=>0))) {
74             $mainadmin = $user;
75             break;
76         }
77     }
79     if ($mainadmin) {
80         $prevadmins = $CFG->siteadmins;
81         return clone($mainadmin);
82     } else {
83         // this should not happen
84         return false;
85     }
86 }
88 /**
89  * Returns list of all admins, using 1 DB query
90  *
91  * @return array
92  */
93 function get_admins() {
94     global $DB, $CFG;
96     if (empty($CFG->siteadmins)) {  // Should not happen on an ordinary site
97         return array();
98     }
100     $sql = "SELECT u.*
101               FROM {user} u
102              WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
104     // We want the same order as in $CFG->siteadmins.
105     $records = $DB->get_records_sql($sql);
106     $admins = array();
107     foreach (explode(',', $CFG->siteadmins) as $id) {
108         $id = (int)$id;
109         if (!isset($records[$id])) {
110             // User does not exist, this should not happen.
111             continue;
112         }
113         $admins[$records[$id]->id] = $records[$id];
114     }
116     return $admins;
119 /**
120  * Search through course users
121  *
122  * If $coursid specifies the site course then this function searches
123  * through all undeleted and confirmed users
124  *
125  * @global object
126  * @uses SITEID
127  * @uses SQL_PARAMS_NAMED
128  * @uses CONTEXT_COURSE
129  * @param int $courseid The course in question.
130  * @param int $groupid The group in question.
131  * @param string $searchtext The string to search for
132  * @param string $sort A field to sort by
133  * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
134  * @return array
135  */
136 function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
137     global $DB;
139     $fullname  = $DB->sql_fullname('u.firstname', 'u.lastname');
141     if (!empty($exceptions)) {
142         list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
143         $except = "AND u.id $exceptions";
144     } else {
145         $except = "";
146         $params = array();
147     }
149     if (!empty($sort)) {
150         $order = "ORDER BY $sort";
151     } else {
152         $order = "";
153     }
155     $select = "u.deleted = 0 AND u.confirmed = 1 AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
156     $params['search1'] = "%$searchtext%";
157     $params['search2'] = "%$searchtext%";
159     if (!$courseid or $courseid == SITEID) {
160         $sql = "SELECT u.id, u.firstname, u.lastname, u.email
161                   FROM {user} u
162                  WHERE $select
163                        $except
164                 $order";
165         return $DB->get_records_sql($sql, $params);
167     } else {
168         if ($groupid) {
169             $sql = "SELECT u.id, u.firstname, u.lastname, u.email
170                       FROM {user} u
171                       JOIN {groups_members} gm ON gm.userid = u.id
172                      WHERE $select AND gm.groupid = :groupid
173                            $except
174                      $order";
175             $params['groupid'] = $groupid;
176             return $DB->get_records_sql($sql, $params);
178         } else {
179             $context = context_course::instance($courseid);
181             // We want to query both the current context and parent contexts.
182             list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
184             $sql = "SELECT u.id, u.firstname, u.lastname, u.email
185                       FROM {user} u
186                       JOIN {role_assignments} ra ON ra.userid = u.id
187                      WHERE $select AND ra.contextid $relatedctxsql
188                            $except
189                     $order";
190             $params = array_merge($params, $relatedctxparams);
191             return $DB->get_records_sql($sql, $params);
192         }
193     }
196 /**
197  * Returns SQL used to search through user table to find users (in a query
198  * which may also join and apply other conditions).
199  *
200  * You can combine this SQL with an existing query by adding 'AND $sql' to the
201  * WHERE clause of your query (where $sql is the first element in the array
202  * returned by this function), and merging in the $params array to the parameters
203  * of your query (where $params is the second element). Your query should use
204  * named parameters such as :param, rather than the question mark style.
205  *
206  * There are examples of basic usage in the unit test for this function.
207  *
208  * @param string $search the text to search for (empty string = find all)
209  * @param string $u the table alias for the user table in the query being
210  *     built. May be ''.
211  * @param bool $searchanywhere If true (default), searches in the middle of
212  *     names, otherwise only searches at start
213  * @param array $extrafields Array of extra user fields to include in search
214  * @param array $exclude Array of user ids to exclude (empty = don't exclude)
215  * @param array $includeonly If specified, only returns users that have ids
216  *     incldued in this array (empty = don't restrict)
217  * @return array an array with two elements, a fragment of SQL to go in the
218  *     where clause the query, and an associative array containing any required
219  *     parameters (using named placeholders).
220  */
221 function users_search_sql($search, $u = 'u', $searchanywhere = true, array $extrafields = array(),
222         array $exclude = null, array $includeonly = null) {
223     global $DB, $CFG;
224     $params = array();
225     $tests = array();
227     if ($u) {
228         $u .= '.';
229     }
231     // If we have a $search string, put a field LIKE '$search%' condition on each field.
232     if ($search) {
233         $conditions = array(
234             $DB->sql_fullname($u . 'firstname', $u . 'lastname'),
235             $conditions[] = $u . 'lastname'
236         );
237         foreach ($extrafields as $field) {
238             $conditions[] = $u . $field;
239         }
240         if ($searchanywhere) {
241             $searchparam = '%' . $search . '%';
242         } else {
243             $searchparam = $search . '%';
244         }
245         $i = 0;
246         foreach ($conditions as $key => $condition) {
247             $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false, false);
248             $params["con{$i}00"] = $searchparam;
249             $i++;
250         }
251         $tests[] = '(' . implode(' OR ', $conditions) . ')';
252     }
254     // Add some additional sensible conditions.
255     $tests[] = $u . "id <> :guestid";
256     $params['guestid'] = $CFG->siteguest;
257     $tests[] = $u . 'deleted = 0';
258     $tests[] = $u . 'confirmed = 1';
260     // If we are being asked to exclude any users, do that.
261     if (!empty($exclude)) {
262         list($usertest, $userparams) = $DB->get_in_or_equal($exclude, SQL_PARAMS_NAMED, 'ex', false);
263         $tests[] = $u . 'id ' . $usertest;
264         $params = array_merge($params, $userparams);
265     }
267     // If we are validating a set list of userids, add an id IN (...) test.
268     if (!empty($includeonly)) {
269         list($usertest, $userparams) = $DB->get_in_or_equal($includeonly, SQL_PARAMS_NAMED, 'val');
270         $tests[] = $u . 'id ' . $usertest;
271         $params = array_merge($params, $userparams);
272     }
274     // In case there are no tests, add one result (this makes it easier to combine
275     // this with an existing query as you can always add AND $sql).
276     if (empty($tests)) {
277         $tests[] = '1 = 1';
278     }
280     // Combing the conditions and return.
281     return array(implode(' AND ', $tests), $params);
285 /**
286  * This function generates the standard ORDER BY clause for use when generating
287  * lists of users. If you don't have a reason to use a different order, then
288  * you should use this method to generate the order when displaying lists of users.
289  *
290  * If the optional $search parameter is passed, then exact matches to the search
291  * will be sorted first. For example, suppose you have two users 'Al Zebra' and
292  * 'Alan Aardvark'. The default sort is Alan, then Al. If, however, you search for
293  * 'Al', then Al will be listed first. (With two users, this is not a big deal,
294  * but with thousands of users, it is essential.)
295  *
296  * The list of fields scanned for exact matches are:
297  *  - firstname
298  *  - lastname
299  *  - $DB->sql_fullname
300  *  - those returned by get_extra_user_fields
301  *
302  * If named parameters are used (which is the default, and highly recommended),
303  * then the parameter names are like :usersortexactN, where N is an int.
304  *
305  * The simplest possible example use is:
306  * list($sort, $params) = users_order_by_sql();
307  * $sql = 'SELECT * FROM {users} ORDER BY ' . $sort;
308  *
309  * A more complex example, showing that this sort can be combined with other sorts:
310  * list($sort, $sortparams) = users_order_by_sql('u');
311  * $sql = "SELECT g.id AS groupid, gg.groupingid, u.id AS userid, u.firstname, u.lastname, u.idnumber, u.username
312  *           FROM {groups} g
313  *      LEFT JOIN {groupings_groups} gg ON g.id = gg.groupid
314  *      LEFT JOIN {groups_members} gm ON g.id = gm.groupid
315  *      LEFT JOIN {user} u ON gm.userid = u.id
316  *          WHERE g.courseid = :courseid $groupwhere $groupingwhere
317  *       ORDER BY g.name, $sort";
318  * $params += $sortparams;
319  *
320  * An example showing the use of $search:
321  * list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
322  * $order = ' ORDER BY ' . $sort;
323  * $params += $sortparams;
324  * $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
325  *
326  * @param string $usertablealias (optional) any table prefix for the {users} table. E.g. 'u'.
327  * @param string $search (optional) a current search string. If given,
328  *      any exact matches to this string will be sorted first.
329  * @param context $context the context we are in. Use by get_extra_user_fields.
330  *      Defaults to $PAGE->context.
331  * @return array with two elements:
332  *      string SQL fragment to use in the ORDER BY clause. For example, "firstname, lastname".
333  *      array of parameters used in the SQL fragment.
334  */
335 function users_order_by_sql($usertablealias = '', $search = null, context $context = null) {
336     global $DB, $PAGE;
338     if ($usertablealias) {
339         $tableprefix = $usertablealias . '.';
340     } else {
341         $tableprefix = '';
342     }
344     $sort = "{$tableprefix}lastname, {$tableprefix}firstname, {$tableprefix}id";
345     $params = array();
347     if (!$search) {
348         return array($sort, $params);
349     }
351     if (!$context) {
352         $context = $PAGE->context;
353     }
355     $exactconditions = array();
356     $paramkey = 'usersortexact1';
358     $exactconditions[] = $DB->sql_fullname($tableprefix . 'firstname', $tableprefix  . 'lastname') .
359             ' = :' . $paramkey;
360     $params[$paramkey] = $search;
361     $paramkey++;
363     $fieldstocheck = array_merge(array('firstname', 'lastname'), get_extra_user_fields($context));
364     foreach ($fieldstocheck as $key => $field) {
365         $exactconditions[] = 'LOWER(' . $tableprefix . $field . ') = LOWER(:' . $paramkey . ')';
366         $params[$paramkey] = $search;
367         $paramkey++;
368     }
370     $sort = 'CASE WHEN ' . implode(' OR ', $exactconditions) .
371             ' THEN 0 ELSE 1 END, ' . $sort;
373     return array($sort, $params);
376 /**
377  * Returns a subset of users
378  *
379  * @global object
380  * @uses DEBUG_DEVELOPER
381  * @uses SQL_PARAMS_NAMED
382  * @param bool $get If false then only a count of the records is returned
383  * @param string $search A simple string to search for
384  * @param bool $confirmed A switch to allow/disallow unconfirmed users
385  * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
386  * @param string $sort A SQL snippet for the sorting criteria to use
387  * @param string $firstinitial Users whose first name starts with $firstinitial
388  * @param string $lastinitial Users whose last name starts with $lastinitial
389  * @param string $page The page or records to return
390  * @param string $recordsperpage The number of records to return per page
391  * @param string $fields A comma separated list of fields to be returned from the chosen table.
392  * @return array|int|bool  {@link $USER} records unless get is false in which case the integer count of the records found is returned.
393  *                        False is returned if an error is encountered.
394  */
395 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
396                    $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
397     global $DB, $CFG;
399     if ($get && !$recordsperpage) {
400         debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
401                 'On large installations, this will probably cause an out of memory error. ' .
402                 'Please think again and change your code so that it does not try to ' .
403                 'load so much data into memory.', DEBUG_DEVELOPER);
404     }
406     $fullname  = $DB->sql_fullname();
408     $select = " id <> :guestid AND deleted = 0";
409     $params = array('guestid'=>$CFG->siteguest);
411     if (!empty($search)){
412         $search = trim($search);
413         $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
414         $params['search1'] = "%$search%";
415         $params['search2'] = "%$search%";
416         $params['search3'] = "$search";
417     }
419     if ($confirmed) {
420         $select .= " AND confirmed = 1";
421     }
423     if ($exceptions) {
424         list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
425         $params = $params + $eparams;
426         $select .= " AND id $exceptions";
427     }
429     if ($firstinitial) {
430         $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
431         $params['fni'] = "$firstinitial%";
432     }
433     if ($lastinitial) {
434         $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
435         $params['lni'] = "$lastinitial%";
436     }
438     if ($extraselect) {
439         $select .= " AND $extraselect";
440         $params = $params + (array)$extraparams;
441     }
443     if ($get) {
444         return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
445     } else {
446         return $DB->count_records_select('user', $select, $params);
447     }
451 /**
452  * Return filtered (if provided) list of users in site, except guest and deleted users.
453  *
454  * @param string $sort An SQL field to sort by
455  * @param string $dir The sort direction ASC|DESC
456  * @param int $page The page or records to return
457  * @param int $recordsperpage The number of records to return per page
458  * @param string $search A simple string to search for
459  * @param string $firstinitial Users whose first name starts with $firstinitial
460  * @param string $lastinitial Users whose last name starts with $lastinitial
461  * @param string $extraselect An additional SQL select statement to append to the query
462  * @param array $extraparams Additional parameters to use for the above $extraselect
463  * @param stdClass $extracontext If specified, will include user 'extra fields'
464  *   as appropriate for current user and given context
465  * @return array Array of {@link $USER} records
466  */
467 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
468                            $search='', $firstinitial='', $lastinitial='', $extraselect='',
469                            array $extraparams=null, $extracontext = null) {
470     global $DB, $CFG;
472     $fullname  = $DB->sql_fullname();
474     $select = "deleted <> 1 AND id <> :guestid";
475     $params = array('guestid' => $CFG->siteguest);
477     if (!empty($search)) {
478         $search = trim($search);
479         $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
480                    " OR ". $DB->sql_like('email', ':search2', false, false).
481                    " OR username = :search3)";
482         $params['search1'] = "%$search%";
483         $params['search2'] = "%$search%";
484         $params['search3'] = "$search";
485     }
487     if ($firstinitial) {
488         $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
489         $params['fni'] = "$firstinitial%";
490     }
491     if ($lastinitial) {
492         $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
493         $params['lni'] = "$lastinitial%";
494     }
496     if ($extraselect) {
497         $select .= " AND $extraselect";
498         $params = $params + (array)$extraparams;
499     }
501     if ($sort) {
502         $sort = " ORDER BY $sort $dir";
503     }
505     // If a context is specified, get extra user fields that the current user
506     // is supposed to see.
507     $extrafields = '';
508     if ($extracontext) {
509         $extrafields = get_extra_user_fields_sql($extracontext, '', '',
510                 array('id', 'username', 'email', 'firstname', 'lastname', 'city', 'country',
511                 'lastaccess', 'confirmed', 'mnethostid'));
512     }
513     $namefields = get_all_user_name_fields(true);
514     $extrafields = "$extrafields, $namefields";
516     // warning: will return UNCONFIRMED USERS
517     return $DB->get_records_sql("SELECT id, username, email, city, country, lastaccess, confirmed, mnethostid, suspended $extrafields
518                                    FROM {user}
519                                   WHERE $select
520                                   $sort", $params, $page, $recordsperpage);
525 /**
526  * Full list of users that have confirmed their accounts.
527  *
528  * @global object
529  * @return array of unconfirmed users
530  */
531 function get_users_confirmed() {
532     global $DB, $CFG;
533     return $DB->get_records_sql("SELECT *
534                                    FROM {user}
535                                   WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
539 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
542 /**
543  * Returns $course object of the top-level site.
544  *
545  * @return object A {@link $COURSE} object for the site, exception if not found
546  */
547 function get_site() {
548     global $SITE, $DB;
550     if (!empty($SITE->id)) {   // We already have a global to use, so return that
551         return $SITE;
552     }
554     if ($course = $DB->get_record('course', array('category'=>0))) {
555         return $course;
556     } else {
557         // course table exists, but the site is not there,
558         // unfortunately there is no automatic way to recover
559         throw new moodle_exception('nosite', 'error');
560     }
563 /**
564  * Gets a course object from database. If the course id corresponds to an
565  * already-loaded $COURSE or $SITE object, then the loaded object will be used,
566  * saving a database query.
567  *
568  * If it reuses an existing object, by default the object will be cloned. This
569  * means you can modify the object safely without affecting other code.
570  *
571  * @param int $courseid Course id
572  * @param bool $clone If true (default), makes a clone of the record
573  * @return stdClass A course object
574  * @throws dml_exception If not found in database
575  */
576 function get_course($courseid, $clone = true) {
577     global $DB, $COURSE, $SITE;
578     if (!empty($COURSE->id) && $COURSE->id == $courseid) {
579         return $clone ? clone($COURSE) : $COURSE;
580     } else if (!empty($SITE->id) && $SITE->id == $courseid) {
581         return $clone ? clone($SITE) : $SITE;
582     } else {
583         return $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
584     }
587 /**
588  * Updates a course record in database. If the update affects the global $COURSE
589  * or $SITE, then these variables are also changed.
590  *
591  * @param stdClass $courserec Course record
592  * @throws dml_exception If error updating database
593  */
594 function update_course_record($courserec) {
595     global $DB, $COURSE, $SITE;
596     $DB->update_record('course', $courserec);
597     if (!empty($COURSE->id) && $COURSE->id == $courserec->id) {
598         foreach ((array)$courserec as $name => $value) {
599             $COURSE->{$name} = $value;
600         }
601     } else if (!empty($SITE->id) && $SITE->id == $courserec->id) {
602         foreach ((array)$courserec as $name => $value) {
603             $SITE->{$name} = $value;
604         }
605     }
608 /**
609  * Returns list of courses, for whole site, or category
610  *
611  * Returns list of courses, for whole site, or category
612  * Important: Using c.* for fields is extremely expensive because
613  *            we are using distinct. You almost _NEVER_ need all the fields
614  *            in such a large SELECT
615  *
616  * @global object
617  * @global object
618  * @global object
619  * @uses CONTEXT_COURSE
620  * @param string|int $categoryid Either a category id or 'all' for everything
621  * @param string $sort A field and direction to sort by
622  * @param string $fields The additional fields to return
623  * @return array Array of courses
624  */
625 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
627     global $USER, $CFG, $DB;
629     $params = array();
631     if ($categoryid !== "all" && is_numeric($categoryid)) {
632         $categoryselect = "WHERE c.category = :catid";
633         $params['catid'] = $categoryid;
634     } else {
635         $categoryselect = "";
636     }
638     if (empty($sort)) {
639         $sortstatement = "";
640     } else {
641         $sortstatement = "ORDER BY $sort";
642     }
644     $visiblecourses = array();
646     $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
647     $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
648     $params['contextlevel'] = CONTEXT_COURSE;
650     $sql = "SELECT $fields $ccselect
651               FROM {course} c
652            $ccjoin
653               $categoryselect
654               $sortstatement";
656     // pull out all course matching the cat
657     if ($courses = $DB->get_records_sql($sql, $params)) {
659         // loop throught them
660         foreach ($courses as $course) {
661             context_helper::preload_from_record($course);
662             if (isset($course->visible) && $course->visible <= 0) {
663                 // for hidden courses, require visibility check
664                 if (has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
665                     $visiblecourses [$course->id] = $course;
666                 }
667             } else {
668                 $visiblecourses [$course->id] = $course;
669             }
670         }
671     }
672     return $visiblecourses;
676 /**
677  * Returns list of courses, for whole site, or category
678  *
679  * Similar to get_courses, but allows paging
680  * Important: Using c.* for fields is extremely expensive because
681  *            we are using distinct. You almost _NEVER_ need all the fields
682  *            in such a large SELECT
683  *
684  * @global object
685  * @global object
686  * @global object
687  * @uses CONTEXT_COURSE
688  * @param string|int $categoryid Either a category id or 'all' for everything
689  * @param string $sort A field and direction to sort by
690  * @param string $fields The additional fields to return
691  * @param int $totalcount Reference for the number of courses
692  * @param string $limitfrom The course to start from
693  * @param string $limitnum The number of courses to limit to
694  * @return array Array of courses
695  */
696 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
697                           &$totalcount, $limitfrom="", $limitnum="") {
698     global $USER, $CFG, $DB;
700     $params = array();
702     $categoryselect = "";
703     if ($categoryid !== "all" && is_numeric($categoryid)) {
704         $categoryselect = "WHERE c.category = :catid";
705         $params['catid'] = $categoryid;
706     } else {
707         $categoryselect = "";
708     }
710     $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
711     $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
712     $params['contextlevel'] = CONTEXT_COURSE;
714     $totalcount = 0;
715     if (!$limitfrom) {
716         $limitfrom = 0;
717     }
718     $visiblecourses = array();
720     $sql = "SELECT $fields $ccselect
721               FROM {course} c
722               $ccjoin
723            $categoryselect
724           ORDER BY $sort";
726     // pull out all course matching the cat
727     $rs = $DB->get_recordset_sql($sql, $params);
728     // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
729     foreach($rs as $course) {
730         context_helper::preload_from_record($course);
731         if ($course->visible <= 0) {
732             // for hidden courses, require visibility check
733             if (has_capability('moodle/course:viewhiddencourses', context_course::instance($course->id))) {
734                 $totalcount++;
735                 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
736                     $visiblecourses [$course->id] = $course;
737                 }
738             }
739         } else {
740             $totalcount++;
741             if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
742                 $visiblecourses [$course->id] = $course;
743             }
744         }
745     }
746     $rs->close();
747     return $visiblecourses;
750 /**
751  * A list of courses that match a search
752  *
753  * @global object
754  * @global object
755  * @param array $searchterms An array of search criteria
756  * @param string $sort A field and direction to sort by
757  * @param int $page The page number to get
758  * @param int $recordsperpage The number of records per page
759  * @param int $totalcount Passed in by reference.
760  * @return object {@link $COURSE} records
761  */
762 function get_courses_search($searchterms, $sort, $page, $recordsperpage, &$totalcount) {
763     global $CFG, $DB;
765     if ($DB->sql_regex_supported()) {
766         $REGEXP    = $DB->sql_regex(true);
767         $NOTREGEXP = $DB->sql_regex(false);
768     }
770     $searchcond = array();
771     $params     = array();
772     $i = 0;
774     // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
775     if ($DB->get_dbfamily() == 'oracle') {
776         $concat = "(c.summary|| ' ' || c.fullname || ' ' || c.idnumber || ' ' || c.shortname)";
777     } else {
778         $concat = $DB->sql_concat("COALESCE(c.summary, '')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
779     }
781     foreach ($searchterms as $searchterm) {
782         $i++;
784         $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
785                    /// will use it to simulate the "-" operator with LIKE clause
787     /// Under Oracle and MSSQL, trim the + and - operators and perform
788     /// simpler LIKE (or NOT LIKE) queries
789         if (!$DB->sql_regex_supported()) {
790             if (substr($searchterm, 0, 1) == '-') {
791                 $NOT = true;
792             }
793             $searchterm = trim($searchterm, '+-');
794         }
796         // TODO: +- may not work for non latin languages
798         if (substr($searchterm,0,1) == '+') {
799             $searchterm = trim($searchterm, '+-');
800             $searchterm = preg_quote($searchterm, '|');
801             $searchcond[] = "$concat $REGEXP :ss$i";
802             $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
804         } else if (substr($searchterm,0,1) == "-") {
805             $searchterm = trim($searchterm, '+-');
806             $searchterm = preg_quote($searchterm, '|');
807             $searchcond[] = "$concat $NOTREGEXP :ss$i";
808             $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
810         } else {
811             $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
812             $params['ss'.$i] = "%$searchterm%";
813         }
814     }
816     if (empty($searchcond)) {
817         $totalcount = 0;
818         return array();
819     }
821     $searchcond = implode(" AND ", $searchcond);
823     $courses = array();
824     $c = 0; // counts how many visible courses we've seen
826     // Tiki pagination
827     $limitfrom = $page * $recordsperpage;
828     $limitto   = $limitfrom + $recordsperpage;
830     $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
831     $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
832     $params['contextlevel'] = CONTEXT_COURSE;
834     $fields = array_diff(array_keys($DB->get_columns('course')), array('modinfo', 'sectioncache'));
835     $sql = "SELECT c.".join(',c.',$fields)." $ccselect
836               FROM {course} c
837            $ccjoin
838              WHERE $searchcond AND c.id <> ".SITEID."
839           ORDER BY $sort";
841     $rs = $DB->get_recordset_sql($sql, $params);
842     foreach($rs as $course) {
843         if (!$course->visible) {
844             // preload contexts only for hidden courses or courses we need to return
845             context_helper::preload_from_record($course);
846             $coursecontext = context_course::instance($course->id);
847             if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
848                 continue;
849             }
850         }
851         // Don't exit this loop till the end
852         // we need to count all the visible courses
853         // to update $totalcount
854         if ($c >= $limitfrom && $c < $limitto) {
855             $courses[$course->id] = $course;
856         }
857         $c++;
858     }
859     $rs->close();
861     // our caller expects 2 bits of data - our return
862     // array, and an updated $totalcount
863     $totalcount = $c;
864     return $courses;
867 /**
868  * Fixes course category and course sortorder, also verifies category and course parents and paths.
869  * (circular references are not fixed)
870  *
871  * @global object
872  * @global object
873  * @uses MAX_COURSES_IN_CATEGORY
874  * @uses MAX_COURSE_CATEGORIES
875  * @uses SITEID
876  * @uses CONTEXT_COURSE
877  * @return void
878  */
879 function fix_course_sortorder() {
880     global $DB, $SITE;
882     //WARNING: this is PHP5 only code!
884     // if there are any changes made to courses or categories we will trigger
885     // the cache events to purge all cached courses/categories data
886     $cacheevents = array();
888     if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
889         //move all categories that are not sorted yet to the end
890         $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
891         $cacheevents['changesincoursecat'] = true;
892     }
894     $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
895     $topcats    = array();
896     $brokencats = array();
897     foreach ($allcats as $cat) {
898         $sortorder = (int)$cat->sortorder;
899         if (!$cat->parent) {
900             while(isset($topcats[$sortorder])) {
901                 $sortorder++;
902             }
903             $topcats[$sortorder] = $cat;
904             continue;
905         }
906         if (!isset($allcats[$cat->parent])) {
907             $brokencats[] = $cat;
908             continue;
909         }
910         if (!isset($allcats[$cat->parent]->children)) {
911             $allcats[$cat->parent]->children = array();
912         }
913         while(isset($allcats[$cat->parent]->children[$sortorder])) {
914             $sortorder++;
915         }
916         $allcats[$cat->parent]->children[$sortorder] = $cat;
917     }
918     unset($allcats);
920     // add broken cats to category tree
921     if ($brokencats) {
922         $defaultcat = reset($topcats);
923         foreach ($brokencats as $cat) {
924             $topcats[] = $cat;
925         }
926     }
928     // now walk recursively the tree and fix any problems found
929     $sortorder = 0;
930     $fixcontexts = array();
931     if (_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts)) {
932         $cacheevents['changesincoursecat'] = true;
933     }
935     // detect if there are "multiple" frontpage courses and fix them if needed
936     $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
937     if (count($frontcourses) > 1) {
938         if (isset($frontcourses[SITEID])) {
939             $frontcourse = $frontcourses[SITEID];
940             unset($frontcourses[SITEID]);
941         } else {
942             $frontcourse = array_shift($frontcourses);
943         }
944         $defaultcat = reset($topcats);
945         foreach ($frontcourses as $course) {
946             $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
947             $context = context_course::instance($course->id);
948             $fixcontexts[$context->id] = $context;
949             $cacheevents['changesincourse'] = true;
950         }
951         unset($frontcourses);
952     } else {
953         $frontcourse = reset($frontcourses);
954     }
956     // now fix the paths and depths in context table if needed
957     if ($fixcontexts) {
958         foreach ($fixcontexts as $fixcontext) {
959             $fixcontext->reset_paths(false);
960         }
961         context_helper::build_all_paths(false);
962         unset($fixcontexts);
963         $cacheevents['changesincourse'] = true;
964         $cacheevents['changesincoursecat'] = true;
965     }
967     // release memory
968     unset($topcats);
969     unset($brokencats);
970     unset($fixcontexts);
972     // fix frontpage course sortorder
973     if ($frontcourse->sortorder != 1) {
974         $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
975         $cacheevents['changesincourse'] = true;
976     }
978     // now fix the course counts in category records if needed
979     $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
980               FROM {course_categories} cc
981               LEFT JOIN {course} c ON c.category = cc.id
982           GROUP BY cc.id, cc.coursecount
983             HAVING cc.coursecount <> COUNT(c.id)";
985     if ($updatecounts = $DB->get_records_sql($sql)) {
986         // categories with more courses than MAX_COURSES_IN_CATEGORY
987         $categories = array();
988         foreach ($updatecounts as $cat) {
989             $cat->coursecount = $cat->newcount;
990             if ($cat->coursecount >= MAX_COURSES_IN_CATEGORY) {
991                 $categories[] = $cat->id;
992             }
993             unset($cat->newcount);
994             $DB->update_record_raw('course_categories', $cat, true);
995         }
996         if (!empty($categories)) {
997             $str = implode(', ', $categories);
998             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);
999         }
1000         $cacheevents['changesincoursecat'] = true;
1001     }
1003     // now make sure that sortorders in course table are withing the category sortorder ranges
1004     $sql = "SELECT DISTINCT cc.id, cc.sortorder
1005               FROM {course_categories} cc
1006               JOIN {course} c ON c.category = cc.id
1007              WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
1009     if ($fixcategories = $DB->get_records_sql($sql)) {
1010         //fix the course sortorder ranges
1011         foreach ($fixcategories as $cat) {
1012             $sql = "UPDATE {course}
1013                        SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
1014                      WHERE category = ?";
1015             $DB->execute($sql, array($cat->sortorder, $cat->id));
1016         }
1017         $cacheevents['changesincoursecat'] = true;
1018     }
1019     unset($fixcategories);
1021     // categories having courses with sortorder duplicates or having gaps in sortorder
1022     $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
1023               FROM {course} c1
1024               JOIN {course} c2 ON c1.sortorder = c2.sortorder
1025               JOIN {course_categories} cc ON (c1.category = cc.id)
1026              WHERE c1.id <> c2.id";
1027     $fixcategories = $DB->get_records_sql($sql);
1029     $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
1030               FROM {course_categories} cc
1031               JOIN {course} c ON c.category = cc.id
1032           GROUP BY cc.id, cc.sortorder, cc.coursecount
1033             HAVING (MAX(c.sortorder) <>  cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <>  cc.sortorder + 1)";
1034     $gapcategories = $DB->get_records_sql($sql);
1036     foreach ($gapcategories as $cat) {
1037         if (isset($fixcategories[$cat->id])) {
1038             // duplicates detected already
1040         } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
1041             // easy - new course inserted with sortorder 0, the rest is ok
1042             $sql = "UPDATE {course}
1043                        SET sortorder = sortorder + 1
1044                      WHERE category = ?";
1045             $DB->execute($sql, array($cat->id));
1047         } else {
1048             // it needs full resorting
1049             $fixcategories[$cat->id] = $cat;
1050         }
1051         $cacheevents['changesincourse'] = true;
1052     }
1053     unset($gapcategories);
1055     // fix course sortorders in problematic categories only
1056     foreach ($fixcategories as $cat) {
1057         $i = 1;
1058         $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1059         foreach ($courses as $course) {
1060             if ($course->sortorder != $cat->sortorder + $i) {
1061                 $course->sortorder = $cat->sortorder + $i;
1062                 $DB->update_record_raw('course', $course, true);
1063                 $cacheevents['changesincourse'] = true;
1064             }
1065             $i++;
1066         }
1067     }
1069     // advise all caches that need to be rebuilt
1070     foreach (array_keys($cacheevents) as $event) {
1071         cache_helper::purge_by_event($event);
1072     }
1075 /**
1076  * Internal recursive category verification function, do not use directly!
1077  *
1078  * @todo Document the arguments of this function better
1079  *
1080  * @global object
1081  * @uses MAX_COURSES_IN_CATEGORY
1082  * @uses CONTEXT_COURSECAT
1083  * @param array $children
1084  * @param int $sortorder
1085  * @param string $parent
1086  * @param int $depth
1087  * @param string $path
1088  * @param array $fixcontexts
1089  * @return bool if changes were made
1090  */
1091 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1092     global $DB;
1094     $depth++;
1095     $changesmade = false;
1097     foreach ($children as $cat) {
1098         $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1099         $update = false;
1100         if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1101             $cat->parent = $parent;
1102             $cat->depth  = $depth;
1103             $cat->path   = $path.'/'.$cat->id;
1104             $update = true;
1106             // make sure context caches are rebuild and dirty contexts marked
1107             $context = context_coursecat::instance($cat->id);
1108             $fixcontexts[$context->id] = $context;
1109         }
1110         if ($cat->sortorder != $sortorder) {
1111             $cat->sortorder = $sortorder;
1112             $update = true;
1113         }
1114         if ($update) {
1115             $DB->update_record('course_categories', $cat, true);
1116             $changesmade = true;
1117         }
1118         if (isset($cat->children)) {
1119             if (_fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts)) {
1120                 $changesmade = true;
1121             }
1122         }
1123     }
1124     return $changesmade;
1127 /**
1128  * List of remote courses that a user has access to via MNET.
1129  * Works only on the IDP
1130  *
1131  * @global object
1132  * @global object
1133  * @param int @userid The user id to get remote courses for
1134  * @return array Array of {@link $COURSE} of course objects
1135  */
1136 function get_my_remotecourses($userid=0) {
1137     global $DB, $USER;
1139     if (empty($userid)) {
1140         $userid = $USER->id;
1141     }
1143     // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1144     $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1145                    c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1146                    h.name AS hostname
1147               FROM {mnetservice_enrol_courses} c
1148               JOIN (SELECT DISTINCT hostid, remotecourseid
1149                       FROM {mnetservice_enrol_enrolments}
1150                      WHERE userid = ?
1151                    ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1152               JOIN {mnet_host} h ON h.id = c.hostid";
1154     return $DB->get_records_sql($sql, array($userid));
1157 /**
1158  * List of remote hosts that a user has access to via MNET.
1159  * Works on the SP
1160  *
1161  * @global object
1162  * @global object
1163  * @return array|bool Array of host objects or false
1164  */
1165 function get_my_remotehosts() {
1166     global $CFG, $USER;
1168     if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1169         return false; // Return nothing on the IDP
1170     }
1171     if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1172         return $USER->mnet_foreign_host_array;
1173     }
1174     return false;
1177 /**
1178  * This function creates a default separated/connected scale
1179  *
1180  * This function creates a default separated/connected scale
1181  * so there's something in the database.  The locations of
1182  * strings and files is a bit odd, but this is because we
1183  * need to maintain backward compatibility with many different
1184  * existing language translations and older sites.
1185  *
1186  * @global object
1187  * @return void
1188  */
1189 function make_default_scale() {
1190     global $DB;
1192     $defaultscale = new stdClass();
1193     $defaultscale->courseid = 0;
1194     $defaultscale->userid = 0;
1195     $defaultscale->name  = get_string('separateandconnected');
1196     $defaultscale->description = get_string('separateandconnectedinfo');
1197     $defaultscale->scale = get_string('postrating1', 'forum').','.
1198                            get_string('postrating2', 'forum').','.
1199                            get_string('postrating3', 'forum');
1200     $defaultscale->timemodified = time();
1202     $defaultscale->id = $DB->insert_record('scale', $defaultscale);
1203     $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id));
1207 /**
1208  * Returns a menu of all available scales from the site as well as the given course
1209  *
1210  * @global object
1211  * @param int $courseid The id of the course as found in the 'course' table.
1212  * @return array
1213  */
1214 function get_scales_menu($courseid=0) {
1215     global $DB;
1217     $sql = "SELECT id, name
1218               FROM {scale}
1219              WHERE courseid = 0 or courseid = ?
1220           ORDER BY courseid ASC, name ASC";
1221     $params = array($courseid);
1223     if ($scales = $DB->get_records_sql_menu($sql, $params)) {
1224         return $scales;
1225     }
1227     make_default_scale();
1229     return $DB->get_records_sql_menu($sql, $params);
1234 /**
1235  * Given a set of timezone records, put them in the database,  replacing what is there
1236  *
1237  * @global object
1238  * @param array $timezones An array of timezone records
1239  * @return void
1240  */
1241 function update_timezone_records($timezones) {
1242     global $DB;
1244 /// Clear out all the old stuff
1245     $DB->delete_records('timezone');
1247 /// Insert all the new stuff
1248     foreach ($timezones as $timezone) {
1249         if (is_array($timezone)) {
1250             $timezone = (object)$timezone;
1251         }
1252         $DB->insert_record('timezone', $timezone);
1253     }
1257 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1259 /**
1260  * Just gets a raw list of all modules in a course
1261  *
1262  * @global object
1263  * @param int $courseid The id of the course as found in the 'course' table.
1264  * @return array
1265  */
1266 function get_course_mods($courseid) {
1267     global $DB;
1269     if (empty($courseid)) {
1270         return false; // avoid warnings
1271     }
1273     return $DB->get_records_sql("SELECT cm.*, m.name as modname
1274                                    FROM {modules} m, {course_modules} cm
1275                                   WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1276                                 array($courseid)); // no disabled mods
1280 /**
1281  * Given an id of a course module, finds the coursemodule description
1282  *
1283  * @global object
1284  * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1285  * @param int $cmid course module id (id in course_modules table)
1286  * @param int $courseid optional course id for extra validation
1287  * @param bool $sectionnum include relative section number (0,1,2 ...)
1288  * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1289  *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1290  *                        MUST_EXIST means throw exception if no record or multiple records found
1291  * @return stdClass
1292  */
1293 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1294     global $DB;
1296     $params = array('cmid'=>$cmid);
1298     if (!$modulename) {
1299         if (!$modulename = $DB->get_field_sql("SELECT md.name
1300                                                  FROM {modules} md
1301                                                  JOIN {course_modules} cm ON cm.module = md.id
1302                                                 WHERE cm.id = :cmid", $params, $strictness)) {
1303             return false;
1304         }
1305     }
1307     $params['modulename'] = $modulename;
1309     $courseselect = "";
1310     $sectionfield = "";
1311     $sectionjoin  = "";
1313     if ($courseid) {
1314         $courseselect = "AND cm.course = :courseid";
1315         $params['courseid'] = $courseid;
1316     }
1318     if ($sectionnum) {
1319         $sectionfield = ", cw.section AS sectionnum";
1320         $sectionjoin  = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1321     }
1323     $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1324               FROM {course_modules} cm
1325                    JOIN {modules} md ON md.id = cm.module
1326                    JOIN {".$modulename."} m ON m.id = cm.instance
1327                    $sectionjoin
1328              WHERE cm.id = :cmid AND md.name = :modulename
1329                    $courseselect";
1331     return $DB->get_record_sql($sql, $params, $strictness);
1334 /**
1335  * Given an instance number of a module, finds the coursemodule description
1336  *
1337  * @global object
1338  * @param string $modulename name of module type, eg. resource, assignment,...
1339  * @param int $instance module instance number (id in resource, assignment etc. table)
1340  * @param int $courseid optional course id for extra validation
1341  * @param bool $sectionnum include relative section number (0,1,2 ...)
1342  * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1343  *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1344  *                        MUST_EXIST means throw exception if no record or multiple records found
1345  * @return stdClass
1346  */
1347 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1348     global $DB;
1350     $params = array('instance'=>$instance, 'modulename'=>$modulename);
1352     $courseselect = "";
1353     $sectionfield = "";
1354     $sectionjoin  = "";
1356     if ($courseid) {
1357         $courseselect = "AND cm.course = :courseid";
1358         $params['courseid'] = $courseid;
1359     }
1361     if ($sectionnum) {
1362         $sectionfield = ", cw.section AS sectionnum";
1363         $sectionjoin  = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1364     }
1366     $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1367               FROM {course_modules} cm
1368                    JOIN {modules} md ON md.id = cm.module
1369                    JOIN {".$modulename."} m ON m.id = cm.instance
1370                    $sectionjoin
1371              WHERE m.id = :instance AND md.name = :modulename
1372                    $courseselect";
1374     return $DB->get_record_sql($sql, $params, $strictness);
1377 /**
1378  * Returns all course modules of given activity in course
1379  *
1380  * @param string $modulename The module name (forum, quiz, etc.)
1381  * @param int $courseid The course id to get modules for
1382  * @param string $extrafields extra fields starting with m.
1383  * @return array Array of results
1384  */
1385 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1386     global $DB;
1388     if (!empty($extrafields)) {
1389         $extrafields = ", $extrafields";
1390     }
1391     $params = array();
1392     $params['courseid'] = $courseid;
1393     $params['modulename'] = $modulename;
1396     return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1397                                    FROM {course_modules} cm, {modules} md, {".$modulename."} m
1398                                   WHERE cm.course = :courseid AND
1399                                         cm.instance = m.id AND
1400                                         md.name = :modulename AND
1401                                         md.id = cm.module", $params);
1404 /**
1405  * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1406  *
1407  * Returns an array of all the active instances of a particular
1408  * module in given courses, sorted in the order they are defined
1409  * in the course. Returns an empty array on any errors.
1410  *
1411  * The returned objects includle the columns cw.section, cm.visible,
1412  * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1413  *
1414  * @global object
1415  * @global object
1416  * @param string $modulename The name of the module to get instances for
1417  * @param array $courses an array of course objects.
1418  * @param int $userid
1419  * @param int $includeinvisible
1420  * @return array of module instance objects, including some extra fields from the course_modules
1421  *          and course_sections tables, or an empty array if an error occurred.
1422  */
1423 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1424     global $CFG, $DB;
1426     $outputarray = array();
1428     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1429         return $outputarray;
1430     }
1432     list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1433     $params['modulename'] = $modulename;
1435     if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1436                                                  cm.groupmode, cm.groupingid, cm.groupmembersonly
1437                                             FROM {course_modules} cm, {course_sections} cw, {modules} md,
1438                                                  {".$modulename."} m
1439                                            WHERE cm.course $coursessql AND
1440                                                  cm.instance = m.id AND
1441                                                  cm.section = cw.id AND
1442                                                  md.name = :modulename AND
1443                                                  md.id = cm.module", $params)) {
1444         return $outputarray;
1445     }
1447     foreach ($courses as $course) {
1448         $modinfo = get_fast_modinfo($course, $userid);
1450         if (empty($modinfo->instances[$modulename])) {
1451             continue;
1452         }
1454         foreach ($modinfo->instances[$modulename] as $cm) {
1455             if (!$includeinvisible and !$cm->uservisible) {
1456                 continue;
1457             }
1458             if (!isset($rawmods[$cm->id])) {
1459                 continue;
1460             }
1461             $instance = $rawmods[$cm->id];
1462             if (!empty($cm->extra)) {
1463                 $instance->extra = $cm->extra;
1464             }
1465             $outputarray[] = $instance;
1466         }
1467     }
1469     return $outputarray;
1472 /**
1473  * Returns an array of all the active instances of a particular module in a given course,
1474  * sorted in the order they are defined.
1475  *
1476  * Returns an array of all the active instances of a particular
1477  * module in a given course, sorted in the order they are defined
1478  * in the course. Returns an empty array on any errors.
1479  *
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.
1482  *
1483  * Simply calls {@link all_instances_in_courses()} with a single provided course
1484  *
1485  * @param string $modulename The name of the module to get instances for
1486  * @param object $course The course obect.
1487  * @return array of module instance objects, including some extra fields from the course_modules
1488  *          and course_sections tables, or an empty array if an error occurred.
1489  * @param int $userid
1490  * @param int $includeinvisible
1491  */
1492 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1493     return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1497 /**
1498  * Determine whether a module instance is visible within a course
1499  *
1500  * Given a valid module object with info about the id and course,
1501  * and the module's type (eg "forum") returns whether the object
1502  * is visible or not, groupmembersonly visibility not tested
1503  *
1504  * @global object
1506  * @param $moduletype Name of the module eg 'forum'
1507  * @param $module Object which is the instance of the module
1508  * @return bool Success
1509  */
1510 function instance_is_visible($moduletype, $module) {
1511     global $DB;
1513     if (!empty($module->id)) {
1514         $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1515         if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1516                                                FROM {course_modules} cm, {modules} m
1517                                               WHERE cm.course = :courseid AND
1518                                                     cm.module = m.id AND
1519                                                     m.name = :moduletype AND
1520                                                     cm.instance = :moduleid", $params)) {
1522             foreach ($records as $record) { // there should only be one - use the first one
1523                 return $record->visible;
1524             }
1525         }
1526     }
1527     return true;  // visible by default!
1530 /**
1531  * Determine whether a course module is visible within a course,
1532  * this is different from instance_is_visible() - faster and visibility for user
1533  *
1534  * @global object
1535  * @global object
1536  * @uses DEBUG_DEVELOPER
1537  * @uses CONTEXT_MODULE
1538  * @uses CONDITION_MISSING_EXTRATABLE
1539  * @param object $cm object
1540  * @param int $userid empty means current user
1541  * @return bool Success
1542  */
1543 function coursemodule_visible_for_user($cm, $userid=0) {
1544     global $USER,$CFG;
1546     if (empty($cm->id)) {
1547         debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1548         return false;
1549     }
1550     if (empty($userid)) {
1551         $userid = $USER->id;
1552     }
1553     if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', context_module::instance($cm->id), $userid)) {
1554         return false;
1555     }
1556     if ($CFG->enableavailability) {
1557         require_once($CFG->libdir.'/conditionlib.php');
1558         $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE);
1559         if(!$ci->is_available($cm->availableinfo,false,$userid) and
1560             !has_capability('moodle/course:viewhiddenactivities',
1561                 context_module::instance($cm->id), $userid)) {
1562             return false;
1563         }
1564     }
1565     return groups_course_module_visible($cm, $userid);
1571 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1573 /**
1574  * Add an entry to the config log table.
1575  *
1576  * These are "action" focussed rather than web server hits,
1577  * and provide a way to easily reconstruct changes to Moodle configuration.
1578  *
1579  * @package core
1580  * @category log
1581  * @global moodle_database $DB
1582  * @global stdClass $USER
1583  * @param    string  $name     The name of the configuration change action
1584                                For example 'filter_active' when activating or deactivating a filter
1585  * @param    string  $oldvalue The config setting's previous value
1586  * @param    string  $value    The config setting's new value
1587  * @param    string  $plugin   Plugin name, for example a filter name when changing filter configuration
1588  * @return void
1589  */
1590 function add_to_config_log($name, $oldvalue, $value, $plugin) {
1591     global $USER, $DB;
1593     $log = new stdClass();
1594     $log->userid       = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1595     $log->timemodified = time();
1596     $log->name         = $name;
1597     $log->oldvalue  = $oldvalue;
1598     $log->value     = $value;
1599     $log->plugin    = $plugin;
1600     $DB->insert_record('config_log', $log);
1603 /**
1604  * Add an entry to the log table.
1605  *
1606  * Add an entry to the log table.  These are "action" focussed rather
1607  * than web server hits, and provide a way to easily reconstruct what
1608  * any particular student has been doing.
1609  *
1610  * @package core
1611  * @category log
1612  * @global moodle_database $DB
1613  * @global stdClass $CFG
1614  * @global stdClass $USER
1615  * @uses SITEID
1616  * @uses DEBUG_DEVELOPER
1617  * @uses DEBUG_ALL
1618  * @param    int     $courseid  The course id
1619  * @param    string  $module  The module name  e.g. forum, journal, resource, course, user etc
1620  * @param    string  $action  'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1621  * @param    string  $url     The file and parameters used to see the results of the action
1622  * @param    string  $info    Additional description information
1623  * @param    string  $cm      The course_module->id if there is one
1624  * @param    string  $user    If log regards $user other than $USER
1625  * @return void
1626  */
1627 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1628     // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1629     // This is for a good reason: it is the most frequently used DB update function,
1630     // so it has been optimised for speed.
1631     global $DB, $CFG, $USER;
1633     if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
1634         $cm = 0;
1635     }
1637     if ($user) {
1638         $userid = $user;
1639     } else {
1640         if (session_is_loggedinas()) {  // Don't log
1641             return;
1642         }
1643         $userid = empty($USER->id) ? '0' : $USER->id;
1644     }
1646     if (isset($CFG->logguests) and !$CFG->logguests) {
1647         if (!$userid or isguestuser($userid)) {
1648             return;
1649         }
1650     }
1652     $REMOTE_ADDR = getremoteaddr();
1654     $timenow = time();
1655     $info = $info;
1656     if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1657         $url = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
1658     } else {
1659         $url = '';
1660     }
1662     // Restrict length of log lines to the space actually available in the
1663     // database so that it doesn't cause a DB error. Log a warning so that
1664     // developers can avoid doing things which are likely to cause this on a
1665     // routine basis.
1666     if(!empty($info) && core_text::strlen($info)>255) {
1667         $info = core_text::substr($info,0,252).'...';
1668         debugging('Warning: logged very long info',DEBUG_DEVELOPER);
1669     }
1671     // If the 100 field size is changed, also need to alter print_log in course/lib.php
1672     if(!empty($url) && core_text::strlen($url)>100) {
1673         $url = core_text::substr($url,0,97).'...';
1674         debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
1675     }
1677     if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++;};
1679     $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
1680                  'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
1682     try {
1683         $DB->insert_record_raw('log', $log, false);
1684     } catch (dml_exception $e) {
1685         debugging('Error: Could not insert a new entry to the Moodle log. '. $e->error, DEBUG_ALL);
1687         // MDL-11893, alert $CFG->supportemail if insert into log failed
1688         if ($CFG->supportemail and empty($CFG->noemailever)) {
1689             // email_to_user is not usable because email_to_user tries to write to the logs table,
1690             // and this will get caught in an infinite loop, if disk is full
1691             $site = get_site();
1692             $subject = 'Insert into log failed at your moodle site '.$site->fullname;
1693             $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";
1694             $message .= "The failed query parameters are:\n\n" . var_export($log, true);
1696             $lasttime = get_config('admin', 'lastloginserterrormail');
1697             if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
1698                 //using email directly rather than messaging as they may not be able to log in to access a message
1699                 mail($CFG->supportemail, $subject, $message);
1700                 set_config('lastloginserterrormail', time(), 'admin');
1701             }
1702         }
1703     }
1706 /**
1707  * Store user last access times - called when use enters a course or site
1708  *
1709  * @package core
1710  * @category log
1711  * @global stdClass $USER
1712  * @global stdClass $CFG
1713  * @global moodle_database $DB
1714  * @uses LASTACCESS_UPDATE_SECS
1715  * @uses SITEID
1716  * @param int $courseid  empty courseid means site
1717  * @return void
1718  */
1719 function user_accesstime_log($courseid=0) {
1720     global $USER, $CFG, $DB;
1722     if (!isloggedin() or session_is_loggedinas()) {
1723         // no access tracking
1724         return;
1725     }
1727     if (isguestuser()) {
1728         // Do not update guest access times/ips for performance.
1729         return;
1730     }
1732     if (empty($courseid)) {
1733         $courseid = SITEID;
1734     }
1736     $timenow = time();
1738 /// Store site lastaccess time for the current user
1739     if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1740     /// Update $USER->lastaccess for next checks
1741         $USER->lastaccess = $timenow;
1743         $last = new stdClass();
1744         $last->id         = $USER->id;
1745         $last->lastip     = getremoteaddr();
1746         $last->lastaccess = $timenow;
1748         $DB->update_record_raw('user', $last);
1749     }
1751     if ($courseid == SITEID) {
1752     ///  no user_lastaccess for frontpage
1753         return;
1754     }
1756 /// Store course lastaccess times for the current user
1757     if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
1759         $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
1761         if ($lastaccess === false) {
1762             // Update course lastaccess for next checks
1763             $USER->currentcourseaccess[$courseid] = $timenow;
1765             $last = new stdClass();
1766             $last->userid     = $USER->id;
1767             $last->courseid   = $courseid;
1768             $last->timeaccess = $timenow;
1769             $DB->insert_record_raw('user_lastaccess', $last, false);
1771         } else if ($timenow - $lastaccess <  LASTACCESS_UPDATE_SECS) {
1772             // no need to update now, it was updated recently in concurrent login ;-)
1774         } else {
1775             // Update course lastaccess for next checks
1776             $USER->currentcourseaccess[$courseid] = $timenow;
1778             $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
1779         }
1780     }
1783 /**
1784  * Select all log records based on SQL criteria
1785  *
1786  * @package core
1787  * @category log
1788  * @global moodle_database $DB
1789  * @param string $select SQL select criteria
1790  * @param array $params named sql type params
1791  * @param string $order SQL order by clause to sort the records returned
1792  * @param string $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set)
1793  * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set)
1794  * @param int $totalcount Passed in by reference.
1795  * @return array
1796  */
1797 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1798     global $DB;
1800     if ($order) {
1801         $order = "ORDER BY $order";
1802     }
1804     $selectsql = "";
1805     $countsql  = "";
1807     if ($select) {
1808         $select = "WHERE $select";
1809     }
1811     $sql = "SELECT COUNT(*)
1812               FROM {log} l
1813            $select";
1815     $totalcount = $DB->count_records_sql($sql, $params);
1816     $allnames = get_all_user_name_fields(true, 'u');
1817     $sql = "SELECT l.*, $allnames, u.picture
1818               FROM {log} l
1819               LEFT JOIN {user} u ON l.userid = u.id
1820            $select
1821             $order";
1823     return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
1827 /**
1828  * Select all log records for a given course and user
1829  *
1830  * @package core
1831  * @category log
1832  * @global moodle_database $DB
1833  * @uses DAYSECS
1834  * @param int $userid The id of the user as found in the 'user' table.
1835  * @param int $courseid The id of the course as found in the 'course' table.
1836  * @param string $coursestart unix timestamp representing course start date and time.
1837  * @return array
1838  */
1839 function get_logs_usercourse($userid, $courseid, $coursestart) {
1840     global $DB;
1842     $params = array();
1844     $courseselect = '';
1845     if ($courseid) {
1846         $courseselect = "AND course = :courseid";
1847         $params['courseid'] = $courseid;
1848     }
1849     $params['userid'] = $userid;
1850     $$coursestart = (int)$coursestart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1852     return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
1853                                    FROM {log}
1854                                   WHERE userid = :userid
1855                                         AND time > $coursestart $courseselect
1856                                GROUP BY FLOOR((time - $coursestart)/". DAYSECS .")", $params);
1859 /**
1860  * Select all log records for a given course, user, and day
1861  *
1862  * @package core
1863  * @category log
1864  * @global moodle_database $DB
1865  * @uses HOURSECS
1866  * @param int $userid The id of the user as found in the 'user' table.
1867  * @param int $courseid The id of the course as found in the 'course' table.
1868  * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
1869  * @return array
1870  */
1871 function get_logs_userday($userid, $courseid, $daystart) {
1872     global $DB;
1874     $params = array('userid'=>$userid);
1876     $courseselect = '';
1877     if ($courseid) {
1878         $courseselect = "AND course = :courseid";
1879         $params['courseid'] = $courseid;
1880     }
1881     $daystart = (int)$daystart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1883     return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
1884                                    FROM {log}
1885                                   WHERE userid = :userid
1886                                         AND time > $daystart $courseselect
1887                                GROUP BY FLOOR((time - $daystart)/". HOURSECS .") ", $params);
1890 /**
1891  * Returns an object with counts of failed login attempts
1892  *
1893  * Returns information about failed login attempts.  If the current user is
1894  * an admin, then two numbers are returned:  the number of attempts and the
1895  * number of accounts.  For non-admins, only the attempts on the given user
1896  * are shown.
1897  *
1898  * @global moodle_database $DB
1899  * @uses CONTEXT_SYSTEM
1900  * @param string $mode Either 'admin' or 'everybody'
1901  * @param string $username The username we are searching for
1902  * @param string $lastlogin The date from which we are searching
1903  * @return int
1904  */
1905 function count_login_failures($mode, $username, $lastlogin) {
1906     global $DB;
1908     $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
1909     $select = "module='login' AND action='error' AND time > :lastlogin";
1911     $count = new stdClass();
1913     if (is_siteadmin()) {
1914         if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
1915             $count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
1916             return $count;
1917         }
1918     } else if ($mode == 'everybody') {
1919         if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
1920             return $count;
1921         }
1922     }
1923     return NULL;
1927 /// GENERAL HELPFUL THINGS  ///////////////////////////////////
1929 /**
1930  * Dumps a given object's information for debugging purposes
1931  *
1932  * When used in a CLI script, the object's information is written to the standard
1933  * error output stream. When used in a web script, the object is dumped to a
1934  * pre-formatted block with the "notifytiny" CSS class.
1935  *
1936  * @param mixed $object The data to be printed
1937  * @return void output is echo'd
1938  */
1939 function print_object($object) {
1941     // we may need a lot of memory here
1942     raise_memory_limit(MEMORY_EXTRA);
1944     if (CLI_SCRIPT) {
1945         fwrite(STDERR, print_r($object, true));
1946         fwrite(STDERR, PHP_EOL);
1947     } else {
1948         echo html_writer::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
1949     }
1952 /**
1953  * This function is the official hook inside XMLDB stuff to delegate its debug to one
1954  * external function.
1955  *
1956  * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1957  * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1958  *
1959  * @uses DEBUG_DEVELOPER
1960  * @param string $message string contains the error message
1961  * @param object $object object XMLDB object that fired the debug
1962  */
1963 function xmldb_debug($message, $object) {
1965     debugging($message, DEBUG_DEVELOPER);
1968 /**
1969  * @global object
1970  * @uses CONTEXT_COURSECAT
1971  * @return boolean Whether the user can create courses in any category in the system.
1972  */
1973 function user_can_create_courses() {
1974     global $DB;
1975     $catsrs = $DB->get_recordset('course_categories');
1976     foreach ($catsrs as $cat) {
1977         if (has_capability('moodle/course:create', context_coursecat::instance($cat->id))) {
1978             $catsrs->close();
1979             return true;
1980         }
1981     }
1982     $catsrs->close();
1983     return false;