3e31ee2f9dce1584602e5838b475856b0bac6d79
[moodle.git] / lib / datalib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Library of functions for database manipulation.
20  *
21  * Other main libraries:
22  * - weblib.php - functions that produce web output
23  * - moodlelib.php - general-purpose Moodle functions
24  *
25  * @package    core
26  * @subpackage lib
27  * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
28  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29  */
31 defined('MOODLE_INTERNAL') || die();
33 /**
34  * The maximum courses in a category
35  * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
36  */
37 define('MAX_COURSES_IN_CATEGORY', 10000);
39 /**
40   * The maximum number of course categories
41   * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
42   */
43 define('MAX_COURSE_CATEGORIES', 10000);
45 /**
46  * Number of seconds to wait before updating lastaccess information in DB.
47  */
48 define('LASTACCESS_UPDATE_SECS', 60);
50 /**
51  * Returns $user object of the main admin user
52  * primary admin = admin with lowest role_assignment id among admins
53  *
54  * @static stdClass $mainadmin
55  * @return stdClass {@link $USER} record from DB, false if not found
56  */
57 function get_admin() {
58     static $mainadmin = null;
60     if (!isset($mainadmin)) {
61         if (! $admins = get_admins()) {
62             return false;
63         }
64         //TODO: add some admin setting for specifying of THE main admin
65         //      for now return the first assigned admin
66         $mainadmin = reset($admins);
67     }
68     // we must clone this otherwise code outside can break the static var
69     return clone($mainadmin);
70 }
72 /**
73  * Returns list of all admins, using 1 DB query
74  *
75  * @return array
76  */
77 function get_admins() {
78     global $DB, $CFG;
80     if (empty($CFG->siteadmins)) {  // Should not happen on an ordinary site
81         return array();
82     }
84     $sql = "SELECT u.*
85               FROM {user} u
86              WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
88     return $DB->get_records_sql($sql);
89 }
91 /**
92  * Search through course users
93  *
94  * If $coursid specifies the site course then this function searches
95  * through all undeleted and confirmed users
96  *
97  * @global object
98  * @uses SITEID
99  * @uses SQL_PARAMS_NAMED
100  * @uses CONTEXT_COURSE
101  * @param int $courseid The course in question.
102  * @param int $groupid The group in question.
103  * @param string $searchtext The string to search for
104  * @param string $sort A field to sort by
105  * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
106  * @return array
107  */
108 function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
109     global $DB;
111     $fullname  = $DB->sql_fullname('u.firstname', 'u.lastname');
113     if (!empty($exceptions)) {
114         list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
115         $except = "AND u.id $exceptions";
116     } else {
117         $except = "";
118         $params = array();
119     }
121     if (!empty($sort)) {
122         $order = "ORDER BY $sort";
123     } else {
124         $order = "";
125     }
127     $select = "u.deleted = 0 AND u.confirmed = 1 AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
128     $params['search1'] = "%$searchtext%";
129     $params['search2'] = "%$searchtext%";
131     if (!$courseid or $courseid == SITEID) {
132         $sql = "SELECT u.id, u.firstname, u.lastname, u.email
133                   FROM {user} u
134                  WHERE $select
135                        $except
136                 $order";
137         return $DB->get_records_sql($sql, $params);
139     } else {
140         if ($groupid) {
141             $sql = "SELECT u.id, u.firstname, u.lastname, u.email
142                       FROM {user} u
143                       JOIN {groups_members} gm ON gm.userid = u.id
144                      WHERE $select AND gm.groupid = :groupid
145                            $except
146                      $order";
147             $params['groupid'] = $groupid;
148             return $DB->get_records_sql($sql, $params);
150         } else {
151             $context = get_context_instance(CONTEXT_COURSE, $courseid);
152             $contextlists = get_related_contexts_string($context);
154             $sql = "SELECT u.id, u.firstname, u.lastname, u.email
155                       FROM {user} u
156                       JOIN {role_assignments} ra ON ra.userid = u.id
157                      WHERE $select AND ra.contextid $contextlists
158                            $except
159                     $order";
160             return $DB->get_records_sql($sql, $params);
161         }
162     }
165 /**
166  * Returns a subset of users
167  *
168  * @global object
169  * @uses DEBUG_DEVELOPER
170  * @uses SQL_PARAMS_NAMED
171  * @param bool $get If false then only a count of the records is returned
172  * @param string $search A simple string to search for
173  * @param bool $confirmed A switch to allow/disallow unconfirmed users
174  * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
175  * @param string $sort A SQL snippet for the sorting criteria to use
176  * @param string $firstinitial Users whose first name starts with $firstinitial
177  * @param string $lastinitial Users whose last name starts with $lastinitial
178  * @param string $page The page or records to return
179  * @param string $recordsperpage The number of records to return per page
180  * @param string $fields A comma separated list of fields to be returned from the chosen table.
181  * @return array|int|bool  {@link $USER} records unless get is false in which case the integer count of the records found is returned.
182   *                        False is returned if an error is encountered.
183  */
184 function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
185                    $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
186     global $DB, $CFG;
188     if ($get && !$recordsperpage) {
189         debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
190                 'On large installations, this will probably cause an out of memory error. ' .
191                 'Please think again and change your code so that it does not try to ' .
192                 'load so much data into memory.', DEBUG_DEVELOPER);
193     }
195     $fullname  = $DB->sql_fullname();
197     $select = " id <> :guestid AND deleted = 0";
198     $params = array('guestid'=>$CFG->siteguest);
200     if (!empty($search)){
201         $search = trim($search);
202         $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
203         $params['search1'] = "%$search%";
204         $params['search2'] = "%$search%";
205         $params['search3'] = "$search";
206     }
208     if ($confirmed) {
209         $select .= " AND confirmed = 1";
210     }
212     if ($exceptions) {
213         list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
214         $params = $params + $eparams;
215         $except = " AND id $exceptions";
216     }
218     if ($firstinitial) {
219         $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
220         $params['fni'] = "$firstinitial%";
221     }
222     if ($lastinitial) {
223         $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
224         $params['lni'] = "$lastinitial%";
225     }
227     if ($extraselect) {
228         $select .= " AND $extraselect";
229         $params = $params + (array)$extraparams;
230     }
232     if ($get) {
233         return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
234     } else {
235         return $DB->count_records_select('user', $select, $params);
236     }
240 /**
241  * @todo Finish documenting this function
242  *
243  * @param string $sort An SQL field to sort by
244  * @param string $dir The sort direction ASC|DESC
245  * @param int $page The page or records to return
246  * @param int $recordsperpage The number of records to return per page
247  * @param string $search A simple string to search for
248  * @param string $firstinitial Users whose first name starts with $firstinitial
249  * @param string $lastinitial Users whose last name starts with $lastinitial
250  * @param string $extraselect An additional SQL select statement to append to the query
251  * @param array $extraparams Additional parameters to use for the above $extraselect
252  * @return array Array of {@link $USER} records
253  */
255 function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
256                            $search='', $firstinitial='', $lastinitial='', $extraselect='', array $extraparams=null) {
257     global $DB;
259     $fullname  = $DB->sql_fullname();
261     $select = "deleted <> 1";
262     $params = array();
264     if (!empty($search)) {
265         $search = trim($search);
266         $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
267                    " OR ". $DB->sql_like('email', ':search2', false, false).
268                    " OR username = :search3)";
269         $params['search1'] = "%$search%";
270         $params['search2'] = "%$search%";
271         $params['search3'] = "$search";
272     }
274     if ($firstinitial) {
275         $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
276         $params['fni'] = "$firstinitial%";
277     }
278     if ($lastinitial) {
279         $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
280         $params['lni'] = "$lastinitial%";
281     }
283     if ($extraselect) {
284         $select .= " AND $extraselect";
285         $params = $params + (array)$extraparams;
286     }
288     if ($sort) {
289         $sort = " ORDER BY $sort $dir";
290     }
292 /// warning: will return UNCONFIRMED USERS
293     return $DB->get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
294                                    FROM {user}
295                                   WHERE $select
296                                   $sort", $params, $page, $recordsperpage);
301 /**
302  * Full list of users that have confirmed their accounts.
303  *
304  * @global object
305  * @return array of unconfirmed users
306  */
307 function get_users_confirmed() {
308     global $DB, $CFG;
309     return $DB->get_records_sql("SELECT *
310                                    FROM {user}
311                                   WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
315 /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
318 /**
319  * Returns $course object of the top-level site.
320  *
321  * @return object A {@link $COURSE} object for the site, exception if not found
322  */
323 function get_site() {
324     global $SITE, $DB;
326     if (!empty($SITE->id)) {   // We already have a global to use, so return that
327         return $SITE;
328     }
330     if ($course = $DB->get_record('course', array('category'=>0))) {
331         return $course;
332     } else {
333         // course table exists, but the site is not there,
334         // unfortunately there is no automatic way to recover
335         throw new moodle_exception('nosite', 'error');
336     }
339 /**
340  * Returns list of courses, for whole site, or category
341  *
342  * Returns list of courses, for whole site, or category
343  * Important: Using c.* for fields is extremely expensive because
344  *            we are using distinct. You almost _NEVER_ need all the fields
345  *            in such a large SELECT
346  *
347  * @global object
348  * @global object
349  * @global object
350  * @uses CONTEXT_COURSE
351  * @param string|int $categoryid Either a category id or 'all' for everything
352  * @param string $sort A field and direction to sort by
353  * @param string $fields The additional fields to return
354  * @return array Array of courses
355  */
356 function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
358     global $USER, $CFG, $DB;
360     $params = array();
362     if ($categoryid !== "all" && is_numeric($categoryid)) {
363         $categoryselect = "WHERE c.category = :catid";
364         $params['catid'] = $categoryid;
365     } else {
366         $categoryselect = "";
367     }
369     if (empty($sort)) {
370         $sortstatement = "";
371     } else {
372         $sortstatement = "ORDER BY $sort";
373     }
375     $visiblecourses = array();
377     list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
379     $sql = "SELECT $fields $ccselect
380               FROM {course} c
381            $ccjoin
382               $categoryselect
383               $sortstatement";
385     // pull out all course matching the cat
386     if ($courses = $DB->get_records_sql($sql, $params)) {
388         // loop throught them
389         foreach ($courses as $course) {
390             context_instance_preload($course);
391             if (isset($course->visible) && $course->visible <= 0) {
392                 // for hidden courses, require visibility check
393                 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
394                     $visiblecourses [$course->id] = $course;
395                 }
396             } else {
397                 $visiblecourses [$course->id] = $course;
398             }
399         }
400     }
401     return $visiblecourses;
405 /**
406  * Returns list of courses, for whole site, or category
407  *
408  * Similar to get_courses, but allows paging
409  * Important: Using c.* for fields is extremely expensive because
410  *            we are using distinct. You almost _NEVER_ need all the fields
411  *            in such a large SELECT
412  *
413  * @global object
414  * @global object
415  * @global object
416  * @uses CONTEXT_COURSE
417  * @param string|int $categoryid Either a category id or 'all' for everything
418  * @param string $sort A field and direction to sort by
419  * @param string $fields The additional fields to return
420  * @param int $totalcount Reference for the number of courses
421  * @param string $limitfrom The course to start from
422  * @param string $limitnum The number of courses to limit to
423  * @return array Array of courses
424  */
425 function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
426                           &$totalcount, $limitfrom="", $limitnum="") {
427     global $USER, $CFG, $DB;
429     $params = array();
431     $categoryselect = "";
432     if ($categoryid != "all" && is_numeric($categoryid)) {
433         $categoryselect = "WHERE c.category = :catid";
434         $params['catid'] = $categoryid;
435     } else {
436         $categoryselect = "";
437     }
439     list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
441     $totalcount = 0;
442     if (!$limitfrom) {
443         $limitfrom = 0;
444     }
445     $visiblecourses = array();
447     $sql = "SELECT $fields $ccselect
448               FROM {course} c
449               $ccjoin
450            $categoryselect
451           ORDER BY $sort";
453     // pull out all course matching the cat
454     $rs = $DB->get_recordset_sql($sql, $params);
455     // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
456     foreach($rs as $course) {
457         context_instance_preload($course);
458         if ($course->visible <= 0) {
459             // for hidden courses, require visibility check
460             if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
461                 $totalcount++;
462                 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
463                     $visiblecourses [$course->id] = $course;
464                 }
465             }
466         } else {
467             $totalcount++;
468             if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
469                 $visiblecourses [$course->id] = $course;
470             }
471         }
472     }
473     $rs->close();
474     return $visiblecourses;
477 /**
478  * Retrieve course records with the course managers and other related records
479  * that we need for print_course(). This allows print_courses() to do its job
480  * in a constant number of DB queries, regardless of the number of courses,
481  * role assignments, etc.
482  *
483  * The returned array is indexed on c.id, and each course will have
484  * - $course->managers - array containing RA objects that include a $user obj
485  *                       with the minimal fields needed for fullname()
486  *
487  * @global object
488  * @global object
489  * @global object
490  * @uses CONTEXT_COURSE
491  * @uses CONTEXT_SYSTEM
492  * @uses CONTEXT_COURSECAT
493  * @uses SITEID
494  * @param int|string $categoryid Either the categoryid for the courses or 'all'
495  * @param string $sort A SQL sort field and direction
496  * @param array $fields An array of additional fields to fetch
497  * @return array
498  */
499 function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
500     /*
501      * The plan is to
502      *
503      * - Grab the courses JOINed w/context
504      *
505      * - Grab the interesting course-manager RAs
506      *   JOINed with a base user obj and add them to each course
507      *
508      * So as to do all the work in 2 DB queries. The RA+user JOIN
509      * ends up being pretty expensive if it happens over _all_
510      * courses on a large site. (Are we surprised!?)
511      *
512      * So this should _never_ get called with 'all' on a large site.
513      *
514      */
515     global $USER, $CFG, $DB;
517     $params = array();
518     $allcats = false; // bool flag
519     if ($categoryid === 'all') {
520         $categoryclause   = '';
521         $allcats = true;
522     } elseif (is_numeric($categoryid)) {
523         $categoryclause = "c.category = :catid";
524         $params['catid'] = $categoryid;
525     } else {
526         debugging("Could not recognise categoryid = $categoryid");
527         $categoryclause = '';
528     }
530     $basefields = array('id', 'category', 'sortorder',
531                         'shortname', 'fullname', 'idnumber',
532                         'startdate', 'visible',
533                         'newsitems', 'groupmode', 'groupmodeforce');
535     if (!is_null($fields) && is_string($fields)) {
536         if (empty($fields)) {
537             $fields = $basefields;
538         } else {
539             // turn the fields from a string to an array that
540             // get_user_courses_bycap() will like...
541             $fields = explode(',',$fields);
542             $fields = array_map('trim', $fields);
543             $fields = array_unique(array_merge($basefields, $fields));
544         }
545     } elseif (is_array($fields)) {
546         $fields = array_merge($basefields,$fields);
547     }
548     $coursefields = 'c.' .join(',c.', $fields);
550     if (empty($sort)) {
551         $sortstatement = "";
552     } else {
553         $sortstatement = "ORDER BY $sort";
554     }
556     $where = 'WHERE c.id != ' . SITEID;
557     if ($categoryclause !== ''){
558         $where = "$where AND $categoryclause";
559     }
561     // pull out all courses matching the cat
562     list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
563     $sql = "SELECT $coursefields $ccselect
564               FROM {course} c
565            $ccjoin
566                $where
567                $sortstatement";
569     $catpaths = array();
570     $catpath  = NULL;
571     if ($courses = $DB->get_records_sql($sql, $params)) {
572         // loop on courses materialising
573         // the context, and prepping data to fetch the
574         // managers efficiently later...
575         foreach ($courses as $k => $course) {
576             context_instance_preload($course);
577             $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
578             $courses[$k] = $course;
579             $courses[$k]->managers = array();
580             if ($allcats === false) {
581                 // single cat, so take just the first one...
582                 if ($catpath === NULL) {
583                     $catpath = preg_replace(':/\d+$:', '', $coursecontext->path);
584                 }
585             } else {
586                 // chop off the contextid of the course itself
587                 // like dirname() does...
588                 $catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path);
589             }
590         }
591     } else {
592         return array(); // no courses!
593     }
595     $CFG->coursecontact = trim($CFG->coursecontact);
596     if (empty($CFG->coursecontact)) {
597         return $courses;
598     }
600     $managerroles = explode(',', $CFG->coursecontact);
601     $catctxids = '';
602     if (count($managerroles)) {
603         if ($allcats === true) {
604             $catpaths  = array_unique($catpaths);
605             $ctxids = array();
606             foreach ($catpaths as $cpath) {
607                 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
608             }
609             $ctxids = array_unique($ctxids);
610             $catctxids = implode( ',' , $ctxids);
611             unset($catpaths);
612             unset($cpath);
613         } else {
614             // take the ctx path from the first course
615             // as all categories will be the same...
616             $catpath = substr($catpath,1);
617             $catpath = preg_replace(':/\d+$:','',$catpath);
618             $catctxids = str_replace('/',',',$catpath);
619         }
620         if ($categoryclause !== '') {
621             $categoryclause = "AND $categoryclause";
622         }
623         /*
624          * Note: Here we use a LEFT OUTER JOIN that can
625          * "optionally" match to avoid passing a ton of context
626          * ids in an IN() clause. Perhaps a subselect is faster.
627          *
628          * In any case, this SQL is not-so-nice over large sets of
629          * courses with no $categoryclause.
630          *
631          */
632         $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
633                        r.id AS roleid, r.name as rolename,
634                        u.id AS userid, u.firstname, u.lastname
635                   FROM {role_assignments} ra
636                   JOIN {context} ctx ON ra.contextid = ctx.id
637                   JOIN {user} u ON ra.userid = u.id
638                   JOIN {role} r ON ra.roleid = r.id
639                   LEFT OUTER JOIN {course} c
640                        ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
641                 WHERE ( c.id IS NOT NULL";
642         // under certain conditions, $catctxids is NULL
643         if($catctxids == NULL){
644             $sql .= ") ";
645         }else{
646             $sql .= " OR ra.contextid  IN ($catctxids) )";
647         }
649         $sql .= "AND ra.roleid IN ({$CFG->coursecontact})
650                       $categoryclause
651                 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
652         $rs = $DB->get_recordset_sql($sql, $params);
654         // This loop is fairly stupid as it stands - might get better
655         // results doing an initial pass clustering RAs by path.
656         foreach($rs as $ra) {
657             $user = new stdClass;
658             $user->id        = $ra->userid;    unset($ra->userid);
659             $user->firstname = $ra->firstname; unset($ra->firstname);
660             $user->lastname  = $ra->lastname;  unset($ra->lastname);
661             $ra->user = $user;
662             if ($ra->contextlevel == CONTEXT_SYSTEM) {
663                 foreach ($courses as $k => $course) {
664                     $courses[$k]->managers[] = $ra;
665                 }
666             } else if ($ra->contextlevel == CONTEXT_COURSECAT) {
667                 if ($allcats === false) {
668                     // It always applies
669                     foreach ($courses as $k => $course) {
670                         $courses[$k]->managers[] = $ra;
671                     }
672                 } else {
673                     foreach ($courses as $k => $course) {
674                         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
675                         // Note that strpos() returns 0 as "matched at pos 0"
676                         if (strpos($coursecontext->path, $ra->path.'/') === 0) {
677                             // Only add it to subpaths
678                             $courses[$k]->managers[] = $ra;
679                         }
680                     }
681                 }
682             } else { // course-level
683                 if (!array_key_exists($ra->instanceid, $courses)) {
684                     //this course is not in a list, probably a frontpage course
685                     continue;
686                 }
687                 $courses[$ra->instanceid]->managers[] = $ra;
688             }
689         }
690         $rs->close();
691     }
693     return $courses;
696 /**
697  * A list of courses that match a search
698  *
699  * @global object
700  * @global object
701  * @param array $searchterms An array of search criteria
702  * @param string $sort A field and direction to sort by
703  * @param int $page The page number to get
704  * @param int $recordsperpage The number of records per page
705  * @param int $totalcount Passed in by reference.
706  * @return object {@link $COURSE} records
707  */
708 function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
709     global $CFG, $DB;
711     if ($DB->sql_regex_supported()) {
712         $REGEXP    = $DB->sql_regex(true);
713         $NOTREGEXP = $DB->sql_regex(false);
714     }
716     $searchcond = array();
717     $params     = array();
718     $i = 0;
720     $concat = $DB->sql_concat("COALESCE(c.summary, '". $DB->sql_empty() ."')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
722     foreach ($searchterms as $searchterm) {
723         $i++;
725         $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
726                    /// will use it to simulate the "-" operator with LIKE clause
728     /// Under Oracle and MSSQL, trim the + and - operators and perform
729     /// simpler LIKE (or NOT LIKE) queries
730         if (!$DB->sql_regex_supported()) {
731             if (substr($searchterm, 0, 1) == '-') {
732                 $NOT = true;
733             }
734             $searchterm = trim($searchterm, '+-');
735         }
737         // TODO: +- may not work for non latin languages
739         if (substr($searchterm,0,1) == '+') {
740             $searchterm = trim($searchterm, '+-');
741             $searchterm = preg_quote($searchterm, '|');
742             $searchcond[] = "$concat $REGEXP :ss$i";
743             $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
745         } else if (substr($searchterm,0,1) == "-") {
746             $searchterm = trim($searchterm, '+-');
747             $searchterm = preg_quote($searchterm, '|');
748             $searchcond[] = "$concat $NOTREGEXP :ss$i";
749             $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
751         } else {
752             $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
753             $params['ss'.$i] = "%$searchterm%";
754         }
755     }
757     if (empty($searchcond)) {
758         $totalcount = 0;
759         return array();
760     }
762     $searchcond = implode(" AND ", $searchcond);
764     $courses = array();
765     $c = 0; // counts how many visible courses we've seen
767     // Tiki pagination
768     $limitfrom = $page * $recordsperpage;
769     $limitto   = $limitfrom + $recordsperpage;
771     list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
772     $sql = "SELECT c.* $ccselect
773               FROM {course} c
774            $ccjoin
775              WHERE $searchcond AND c.id <> ".SITEID."
776           ORDER BY $sort";
778     $rs = $DB->get_recordset_sql($sql, $params);
779     foreach($rs as $course) {
780         context_instance_preload($course);
781         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
782         if ($course->visible || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
783             // Don't exit this loop till the end
784             // we need to count all the visible courses
785             // to update $totalcount
786             if ($c >= $limitfrom && $c < $limitto) {
787                 $courses[$course->id] = $course;
788             }
789             $c++;
790         }
791     }
792     $rs->close();
794     // our caller expects 2 bits of data - our return
795     // array, and an updated $totalcount
796     $totalcount = $c;
797     return $courses;
801 /**
802  * Returns a sorted list of categories. Each category object has a context
803  * property that is a context object.
804  *
805  * When asking for $parent='none' it will return all the categories, regardless
806  * of depth. Wheen asking for a specific parent, the default is to return
807  * a "shallow" resultset. Pass false to $shallow and it will return all
808  * the child categories as well.
809  *
810  * @global object
811  * @uses CONTEXT_COURSECAT
812  * @param string $parent The parent category if any
813  * @param string $sort the sortorder
814  * @param bool   $shallow - set to false to get the children too
815  * @return array of categories
816  */
817 function get_categories($parent='none', $sort=NULL, $shallow=true) {
818     global $DB;
820     if ($sort === NULL) {
821         $sort = 'ORDER BY cc.sortorder ASC';
822     } elseif ($sort ==='') {
823         // leave it as empty
824     } else {
825         $sort = "ORDER BY $sort";
826     }
828     list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
830     if ($parent === 'none') {
831         $sql = "SELECT cc.* $ccselect
832                   FROM {course_categories} cc
833                $ccjoin
834                 $sort";
835         $params = array();
837     } elseif ($shallow) {
838         $sql = "SELECT cc.* $ccselect
839                   FROM {course_categories} cc
840                $ccjoin
841                  WHERE cc.parent=?
842                 $sort";
843         $params = array($parent);
845     } else {
846         $sql = "SELECT cc.* $ccselect
847                   FROM {course_categories} cc
848                $ccjoin
849                   JOIN {course_categories} ccp
850                        ON ((cc.parent = ccp.id) OR (cc.path LIKE ".$DB->sql_concat('ccp.path',"'/%'")."))
851                  WHERE ccp.id=?
852                 $sort";
853         $params = array($parent);
854     }
855     $categories = array();
857     $rs = $DB->get_recordset_sql($sql, $params);
858     foreach($rs as $cat) {
859         context_instance_preload($cat);
860         $catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->id);
861         if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) {
862             $categories[$cat->id] = $cat;
863         }
864     }
865     $rs->close();
866     return $categories;
870 /**
871  * Returns an array of category ids of all the subcategories for a given
872  * category.
873  *
874  * @global object
875  * @param int $catid - The id of the category whose subcategories we want to find.
876  * @return array of category ids.
877  */
878 function get_all_subcategories($catid) {
879     global $DB;
881     $subcats = array();
883     if ($categories = $DB->get_records('course_categories', array('parent'=>$catid))) {
884         foreach ($categories as $cat) {
885             array_push($subcats, $cat->id);
886             $subcats = array_merge($subcats, get_all_subcategories($cat->id));
887         }
888     }
889     return $subcats;
892 /**
893  * Return specified category, default if given does not exist
894  *
895  * @global object
896  * @uses MAX_COURSES_IN_CATEGORY
897  * @uses CONTEXT_COURSECAT
898  * @uses SYSCONTEXTID
899  * @param int $catid course category id
900  * @return object caregory
901  */
902 function get_course_category($catid=0) {
903     global $DB;
905     $category = false;
907     if (!empty($catid)) {
908         $category = $DB->get_record('course_categories', array('id'=>$catid));
909     }
911     if (!$category) {
912         // the first category is considered default for now
913         if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
914             $category = reset($category);
916         } else {
917             $cat = new stdClass();
918             $cat->name         = get_string('miscellaneous');
919             $cat->depth        = 1;
920             $cat->sortorder    = MAX_COURSES_IN_CATEGORY;
921             $cat->timemodified = time();
922             $catid = $DB->insert_record('course_categories', $cat);
923             // make sure category context exists
924             get_context_instance(CONTEXT_COURSECAT, $catid);
925             mark_context_dirty('/'.SYSCONTEXTID);
926             fix_course_sortorder(); // Required to build course_categories.depth and .path.
927             $category = $DB->get_record('course_categories', array('id'=>$catid));
928         }
929     }
931     return $category;
934 /**
935  * Fixes course category and course sortorder, also verifies category and course parents and paths.
936  * (circular references are not fixed)
937  *
938  * @global object
939  * @global object
940  * @uses MAX_COURSES_IN_CATEGORY
941  * @uses MAX_COURSE_CATEGORIES
942  * @uses SITEID
943  * @uses CONTEXT_COURSE
944  * @return void
945  */
946 function fix_course_sortorder() {
947     global $DB, $SITE;
949     //WARNING: this is PHP5 only code!
951     if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
952         //move all categories that are not sorted yet to the end
953         $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
954     }
956     $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
957     $topcats    = array();
958     $brokencats = array();
959     foreach ($allcats as $cat) {
960         $sortorder = (int)$cat->sortorder;
961         if (!$cat->parent) {
962             while(isset($topcats[$sortorder])) {
963                 $sortorder++;
964             }
965             $topcats[$sortorder] = $cat;
966             continue;
967         }
968         if (!isset($allcats[$cat->parent])) {
969             $brokencats[] = $cat;
970             continue;
971         }
972         if (!isset($allcats[$cat->parent]->children)) {
973             $allcats[$cat->parent]->children = array();
974         }
975         while(isset($allcats[$cat->parent]->children[$sortorder])) {
976             $sortorder++;
977         }
978         $allcats[$cat->parent]->children[$sortorder] = $cat;
979     }
980     unset($allcats);
982     // add broken cats to category tree
983     if ($brokencats) {
984         $defaultcat = reset($topcats);
985         foreach ($brokencats as $cat) {
986             $topcats[] = $cat;
987         }
988     }
990     // now walk recursively the tree and fix any problems found
991     $sortorder = 0;
992     $fixcontexts = array();
993     _fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts);
995     // detect if there are "multiple" frontpage courses and fix them if needed
996     $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
997     if (count($frontcourses) > 1) {
998         if (isset($frontcourses[SITEID])) {
999             $frontcourse = $frontcourses[SITEID];
1000             unset($frontcourses[SITEID]);
1001         } else {
1002             $frontcourse = array_shift($frontcourses);
1003         }
1004         $defaultcat = reset($topcats);
1005         foreach ($frontcourses as $course) {
1006             $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
1007             $context = get_context_instance(CONTEXT_COURSE, $course->id);
1008             $fixcontexts[$context->id] = $context;
1009         }
1010         unset($frontcourses);
1011     } else {
1012         $frontcourse = reset($frontcourses);
1013     }
1015     // now fix the paths and depths in context table if needed
1016     if ($fixcontexts) {
1017         foreach ($fixcontexts as $fixcontext) {
1018             $fixcontext->reset_paths(false);
1019         }
1020         context_helper::build_all_paths(false);
1021         unset($fixcontexts);
1022     }
1024     // release memory
1025     unset($topcats);
1026     unset($brokencats);
1027     unset($fixcontexts);
1029     // fix frontpage course sortorder
1030     if ($frontcourse->sortorder != 1) {
1031         $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
1032     }
1034     // now fix the course counts in category records if needed
1035     $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
1036               FROM {course_categories} cc
1037               LEFT JOIN {course} c ON c.category = cc.id
1038           GROUP BY cc.id, cc.coursecount
1039             HAVING cc.coursecount <> COUNT(c.id)";
1041     if ($updatecounts = $DB->get_records_sql($sql)) {
1042         // categories with more courses than MAX_COURSES_IN_CATEGORY
1043         $categories = array();
1044         foreach ($updatecounts as $cat) {
1045             $cat->coursecount = $cat->newcount;
1046             if ($cat->coursecount >= MAX_COURSES_IN_CATEGORY) {
1047                 $categories[] = $cat->id;
1048             }
1049             unset($cat->newcount);
1050             $DB->update_record_raw('course_categories', $cat, true);
1051         }
1052         if (!empty($categories)) {
1053             $str = implode(', ', $categories);
1054             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);
1055         }
1056     }
1058     // now make sure that sortorders in course table are withing the category sortorder ranges
1059     $sql = "SELECT DISTINCT cc.id, cc.sortorder
1060               FROM {course_categories} cc
1061               JOIN {course} c ON c.category = cc.id
1062              WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
1064     if ($fixcategories = $DB->get_records_sql($sql)) {
1065         //fix the course sortorder ranges
1066         foreach ($fixcategories as $cat) {
1067             $sql = "UPDATE {course}
1068                        SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
1069                      WHERE category = ?";
1070             $DB->execute($sql, array($cat->sortorder, $cat->id));
1071         }
1072     }
1073     unset($fixcategories);
1075     // categories having courses with sortorder duplicates or having gaps in sortorder
1076     $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
1077               FROM {course} c1
1078               JOIN {course} c2 ON c1.sortorder = c2.sortorder
1079               JOIN {course_categories} cc ON (c1.category = cc.id)
1080              WHERE c1.id <> c2.id";
1081     $fixcategories = $DB->get_records_sql($sql);
1083     $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
1084               FROM {course_categories} cc
1085               JOIN {course} c ON c.category = cc.id
1086           GROUP BY cc.id, cc.sortorder, cc.coursecount
1087             HAVING (MAX(c.sortorder) <>  cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <>  cc.sortorder + 1)";
1088     $gapcategories = $DB->get_records_sql($sql);
1090     foreach ($gapcategories as $cat) {
1091         if (isset($fixcategories[$cat->id])) {
1092             // duplicates detected already
1094         } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
1095             // easy - new course inserted with sortorder 0, the rest is ok
1096             $sql = "UPDATE {course}
1097                        SET sortorder = sortorder + 1
1098                      WHERE category = ?";
1099             $DB->execute($sql, array($cat->id));
1101         } else {
1102             // it needs full resorting
1103             $fixcategories[$cat->id] = $cat;
1104         }
1105     }
1106     unset($gapcategories);
1108     // fix course sortorders in problematic categories only
1109     foreach ($fixcategories as $cat) {
1110         $i = 1;
1111         $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1112         foreach ($courses as $course) {
1113             if ($course->sortorder != $cat->sortorder + $i) {
1114                 $course->sortorder = $cat->sortorder + $i;
1115                 $DB->update_record_raw('course', $course, true);
1116             }
1117             $i++;
1118         }
1119     }
1122 /**
1123  * Internal recursive category verification function, do not use directly!
1124  *
1125  * @todo Document the arguments of this function better
1126  *
1127  * @global object
1128  * @uses MAX_COURSES_IN_CATEGORY
1129  * @uses CONTEXT_COURSECAT
1130  * @param array $children
1131  * @param int $sortorder
1132  * @param string $parent
1133  * @param int $depth
1134  * @param string $path
1135  * @param array $fixcontexts
1136  * @return void
1137  */
1138 function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1139     global $DB;
1141     $depth++;
1143     foreach ($children as $cat) {
1144         $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1145         $update = false;
1146         if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1147             $cat->parent = $parent;
1148             $cat->depth  = $depth;
1149             $cat->path   = $path.'/'.$cat->id;
1150             $update = true;
1152             // make sure context caches are rebuild and dirty contexts marked
1153             $context = get_context_instance(CONTEXT_COURSECAT, $cat->id);
1154             $fixcontexts[$context->id] = $context;
1155         }
1156         if ($cat->sortorder != $sortorder) {
1157             $cat->sortorder = $sortorder;
1158             $update = true;
1159         }
1160         if ($update) {
1161             $DB->update_record('course_categories', $cat, true);
1162         }
1163         if (isset($cat->children)) {
1164             _fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts);
1165         }
1166     }
1169 /**
1170  * List of remote courses that a user has access to via MNET.
1171  * Works only on the IDP
1172  *
1173  * @global object
1174  * @global object
1175  * @param int @userid The user id to get remote courses for
1176  * @return array Array of {@link $COURSE} of course objects
1177  */
1178 function get_my_remotecourses($userid=0) {
1179     global $DB, $USER;
1181     if (empty($userid)) {
1182         $userid = $USER->id;
1183     }
1185     // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1186     $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1187                    c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1188                    h.name AS hostname
1189               FROM {mnetservice_enrol_courses} c
1190               JOIN (SELECT DISTINCT hostid, remotecourseid
1191                       FROM {mnetservice_enrol_enrolments}
1192                      WHERE userid = ?
1193                    ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1194               JOIN {mnet_host} h ON h.id = c.hostid";
1196     return $DB->get_records_sql($sql, array($userid));
1199 /**
1200  * List of remote hosts that a user has access to via MNET.
1201  * Works on the SP
1202  *
1203  * @global object
1204  * @global object
1205  * @return array|bool Array of host objects or false
1206  */
1207 function get_my_remotehosts() {
1208     global $CFG, $USER;
1210     if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1211         return false; // Return nothing on the IDP
1212     }
1213     if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1214         return $USER->mnet_foreign_host_array;
1215     }
1216     return false;
1219 /**
1220  * This function creates a default separated/connected scale
1221  *
1222  * This function creates a default separated/connected scale
1223  * so there's something in the database.  The locations of
1224  * strings and files is a bit odd, but this is because we
1225  * need to maintain backward compatibility with many different
1226  * existing language translations and older sites.
1227  *
1228  * @global object
1229  * @return void
1230  */
1231 function make_default_scale() {
1232     global $DB;
1234     $defaultscale = NULL;
1235     $defaultscale->courseid = 0;
1236     $defaultscale->userid = 0;
1237     $defaultscale->name  = get_string('separateandconnected');
1238     $defaultscale->description = get_string('separateandconnectedinfo');
1239     $defaultscale->scale = get_string('postrating1', 'forum').','.
1240                            get_string('postrating2', 'forum').','.
1241                            get_string('postrating3', 'forum');
1242     $defaultscale->timemodified = time();
1244     $defaultscale->id = $DB->insert_record('scale', $defaultscale);
1245     $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id));
1249 /**
1250  * Returns a menu of all available scales from the site as well as the given course
1251  *
1252  * @global object
1253  * @param int $courseid The id of the course as found in the 'course' table.
1254  * @return array
1255  */
1256 function get_scales_menu($courseid=0) {
1257     global $DB;
1259     $sql = "SELECT id, name
1260               FROM {scale}
1261              WHERE courseid = 0 or courseid = ?
1262           ORDER BY courseid ASC, name ASC";
1263     $params = array($courseid);
1265     if ($scales = $DB->get_records_sql_menu($sql, $params)) {
1266         return $scales;
1267     }
1269     make_default_scale();
1271     return $DB->get_records_sql_menu($sql, $params);
1276 /**
1277  * Given a set of timezone records, put them in the database,  replacing what is there
1278  *
1279  * @global object
1280  * @param array $timezones An array of timezone records
1281  * @return void
1282  */
1283 function update_timezone_records($timezones) {
1284     global $DB;
1286 /// Clear out all the old stuff
1287     $DB->delete_records('timezone');
1289 /// Insert all the new stuff
1290     foreach ($timezones as $timezone) {
1291         if (is_array($timezone)) {
1292             $timezone = (object)$timezone;
1293         }
1294         $DB->insert_record('timezone', $timezone);
1295     }
1299 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1301 /**
1302  * Just gets a raw list of all modules in a course
1303  *
1304  * @global object
1305  * @param int $courseid The id of the course as found in the 'course' table.
1306  * @return array
1307  */
1308 function get_course_mods($courseid) {
1309     global $DB;
1311     if (empty($courseid)) {
1312         return false; // avoid warnings
1313     }
1315     return $DB->get_records_sql("SELECT cm.*, m.name as modname
1316                                    FROM {modules} m, {course_modules} cm
1317                                   WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1318                                 array($courseid)); // no disabled mods
1322 /**
1323  * Given an id of a course module, finds the coursemodule description
1324  *
1325  * @global object
1326  * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1327  * @param int $cmid course module id (id in course_modules table)
1328  * @param int $courseid optional course id for extra validation
1329  * @param bool $sectionnum include relative section number (0,1,2 ...)
1330  * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1331  *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1332  *                        MUST_EXIST means throw exception if no record or multiple records found
1333  * @return stdClass
1334  */
1335 function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1336     global $DB;
1338     $params = array('cmid'=>$cmid);
1340     if (!$modulename) {
1341         if (!$modulename = $DB->get_field_sql("SELECT md.name
1342                                                  FROM {modules} md
1343                                                  JOIN {course_modules} cm ON cm.module = md.id
1344                                                 WHERE cm.id = :cmid", $params, $strictness)) {
1345             return false;
1346         }
1347     }
1349     $params['modulename'] = $modulename;
1351     $courseselect = "";
1352     $sectionfield = "";
1353     $sectionjoin  = "";
1355     if ($courseid) {
1356         $courseselect = "AND cm.course = :courseid";
1357         $params['courseid'] = $courseid;
1358     }
1360     if ($sectionnum) {
1361         $sectionfield = ", cw.section AS sectionnum";
1362         $sectionjoin  = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1363     }
1365     $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1366               FROM {course_modules} cm
1367                    JOIN {modules} md ON md.id = cm.module
1368                    JOIN {".$modulename."} m ON m.id = cm.instance
1369                    $sectionjoin
1370              WHERE cm.id = :cmid AND md.name = :modulename
1371                    $courseselect";
1373     return $DB->get_record_sql($sql, $params, $strictness);
1376 /**
1377  * Given an instance number of a module, finds the coursemodule description
1378  *
1379  * @global object
1380  * @param string $modulename name of module type, eg. resource, assignment,...
1381  * @param int $instance module instance number (id in resource, assignment etc. table)
1382  * @param int $courseid optional course id for extra validation
1383  * @param bool $sectionnum include relative section number (0,1,2 ...)
1384  * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1385  *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1386  *                        MUST_EXIST means throw exception if no record or multiple records found
1387  * @return stdClass
1388  */
1389 function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1390     global $DB;
1392     $params = array('instance'=>$instance, 'modulename'=>$modulename);
1394     $courseselect = "";
1395     $sectionfield = "";
1396     $sectionjoin  = "";
1398     if ($courseid) {
1399         $courseselect = "AND cm.course = :courseid";
1400         $params['courseid'] = $courseid;
1401     }
1403     if ($sectionnum) {
1404         $sectionfield = ", cw.section AS sectionnum";
1405         $sectionjoin  = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1406     }
1408     $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1409               FROM {course_modules} cm
1410                    JOIN {modules} md ON md.id = cm.module
1411                    JOIN {".$modulename."} m ON m.id = cm.instance
1412                    $sectionjoin
1413              WHERE m.id = :instance AND md.name = :modulename
1414                    $courseselect";
1416     return $DB->get_record_sql($sql, $params, $strictness);
1419 /**
1420  * Returns all course modules of given activity in course
1421  *
1422  * @param string $modulename The module name (forum, quiz, etc.)
1423  * @param int $courseid The course id to get modules for
1424  * @param string $extrafields extra fields starting with m.
1425  * @return array Array of results
1426  */
1427 function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1428     global $DB;
1430     if (!empty($extrafields)) {
1431         $extrafields = ", $extrafields";
1432     }
1433     $params = array();
1434     $params['courseid'] = $courseid;
1435     $params['modulename'] = $modulename;
1438     return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1439                                    FROM {course_modules} cm, {modules} md, {".$modulename."} m
1440                                   WHERE cm.course = :courseid AND
1441                                         cm.instance = m.id AND
1442                                         md.name = :modulename AND
1443                                         md.id = cm.module", $params);
1446 /**
1447  * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1448  *
1449  * Returns an array of all the active instances of a particular
1450  * module in given courses, sorted in the order they are defined
1451  * in the course. Returns an empty array on any errors.
1452  *
1453  * The returned objects includle the columns cw.section, cm.visible,
1454  * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1455  *
1456  * @global object
1457  * @global object
1458  * @param string $modulename The name of the module to get instances for
1459  * @param array $courses an array of course objects.
1460  * @param int $userid
1461  * @param int $includeinvisible
1462  * @return array of module instance objects, including some extra fields from the course_modules
1463  *          and course_sections tables, or an empty array if an error occurred.
1464  */
1465 function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1466     global $CFG, $DB;
1468     $outputarray = array();
1470     if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1471         return $outputarray;
1472     }
1474     list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1475     $params['modulename'] = $modulename;
1477     if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1478                                                  cm.groupmode, cm.groupingid, cm.groupmembersonly
1479                                             FROM {course_modules} cm, {course_sections} cw, {modules} md,
1480                                                  {".$modulename."} m
1481                                            WHERE cm.course $coursessql AND
1482                                                  cm.instance = m.id AND
1483                                                  cm.section = cw.id AND
1484                                                  md.name = :modulename AND
1485                                                  md.id = cm.module", $params)) {
1486         return $outputarray;
1487     }
1489     foreach ($courses as $course) {
1490         $modinfo = get_fast_modinfo($course, $userid);
1492         if (empty($modinfo->instances[$modulename])) {
1493             continue;
1494         }
1496         foreach ($modinfo->instances[$modulename] as $cm) {
1497             if (!$includeinvisible and !$cm->uservisible) {
1498                 continue;
1499             }
1500             if (!isset($rawmods[$cm->id])) {
1501                 continue;
1502             }
1503             $instance = $rawmods[$cm->id];
1504             if (!empty($cm->extra)) {
1505                 $instance->extra = $cm->extra;
1506             }
1507             $outputarray[] = $instance;
1508         }
1509     }
1511     return $outputarray;
1514 /**
1515  * Returns an array of all the active instances of a particular module in a given course,
1516  * sorted in the order they are defined.
1517  *
1518  * Returns an array of all the active instances of a particular
1519  * module in a given course, sorted in the order they are defined
1520  * in the course. Returns an empty array on any errors.
1521  *
1522  * The returned objects includle the columns cw.section, cm.visible,
1523  * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1524  *
1525  * Simply calls {@link all_instances_in_courses()} with a single provided course
1526  *
1527  * @param string $modulename The name of the module to get instances for
1528  * @param object $course The course obect.
1529  * @return array of module instance objects, including some extra fields from the course_modules
1530  *          and course_sections tables, or an empty array if an error occurred.
1531  * @param int $userid
1532  * @param int $includeinvisible
1533  */
1534 function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1535     return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1539 /**
1540  * Determine whether a module instance is visible within a course
1541  *
1542  * Given a valid module object with info about the id and course,
1543  * and the module's type (eg "forum") returns whether the object
1544  * is visible or not, groupmembersonly visibility not tested
1545  *
1546  * @global object
1548  * @param $moduletype Name of the module eg 'forum'
1549  * @param $module Object which is the instance of the module
1550  * @return bool Success
1551  */
1552 function instance_is_visible($moduletype, $module) {
1553     global $DB;
1555     if (!empty($module->id)) {
1556         $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1557         if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1558                                                FROM {course_modules} cm, {modules} m
1559                                               WHERE cm.course = :courseid AND
1560                                                     cm.module = m.id AND
1561                                                     m.name = :moduletype AND
1562                                                     cm.instance = :moduleid", $params)) {
1564             foreach ($records as $record) { // there should only be one - use the first one
1565                 return $record->visible;
1566             }
1567         }
1568     }
1569     return true;  // visible by default!
1572 /**
1573  * Determine whether a course module is visible within a course,
1574  * this is different from instance_is_visible() - faster and visibility for user
1575  *
1576  * @global object
1577  * @global object
1578  * @uses DEBUG_DEVELOPER
1579  * @uses CONTEXT_MODULE
1580  * @uses CONDITION_MISSING_EXTRATABLE
1581  * @param object $cm object
1582  * @param int $userid empty means current user
1583  * @return bool Success
1584  */
1585 function coursemodule_visible_for_user($cm, $userid=0) {
1586     global $USER,$CFG;
1588     if (empty($cm->id)) {
1589         debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1590         return false;
1591     }
1592     if (empty($userid)) {
1593         $userid = $USER->id;
1594     }
1595     if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1596         return false;
1597     }
1598     if ($CFG->enableavailability) {
1599         require_once($CFG->libdir.'/conditionlib.php');
1600         $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE);
1601         if(!$ci->is_available($cm->availableinfo,false,$userid) and
1602             !has_capability('moodle/course:viewhiddenactivities',
1603                 get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1604             return false;
1605         }
1606     }
1607     return groups_course_module_visible($cm, $userid);
1613 /// LOG FUNCTIONS /////////////////////////////////////////////////////
1616 /**
1617  * Add an entry to the log table.
1618  *
1619  * Add an entry to the log table.  These are "action" focussed rather
1620  * than web server hits, and provide a way to easily reconstruct what
1621  * any particular student has been doing.
1622  *
1623  * @global object
1624  * @global object
1625  * @global object
1626  * @uses SITEID
1627  * @uses DEBUG_DEVELOPER
1628  * @uses DEBUG_ALL
1629  * @param    int     $courseid  The course id
1630  * @param    string  $module  The module name - e.g. forum, journal, resource, course, user etc
1631  * @param    string  $action  'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
1632  * @param    string  $url     The file and parameters used to see the results of the action
1633  * @param    string  $info    Additional description information
1634  * @param    string  $cm      The course_module->id if there is one
1635  * @param    string  $user    If log regards $user other than $USER
1636  * @return void
1637  */
1638 function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
1639     // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1640     // This is for a good reason: it is the most frequently used DB update function,
1641     // so it has been optimised for speed.
1642     global $DB, $CFG, $USER;
1644     if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
1645         $cm = 0;
1646     }
1648     if ($user) {
1649         $userid = $user;
1650     } else {
1651         if (session_is_loggedinas()) {  // Don't log
1652             return;
1653         }
1654         $userid = empty($USER->id) ? '0' : $USER->id;
1655     }
1657     if (isset($CFG->logguests) and !$CFG->logguests) {
1658         if (!$userid or isguestuser($userid)) {
1659             return;
1660         }
1661     }
1663     $REMOTE_ADDR = getremoteaddr();
1665     $timenow = time();
1666     $info = $info;
1667     if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1668         $url = html_entity_decode($url);
1669     } else {
1670         $url = '';
1671     }
1673     // Restrict length of log lines to the space actually available in the
1674     // database so that it doesn't cause a DB error. Log a warning so that
1675     // developers can avoid doing things which are likely to cause this on a
1676     // routine basis.
1677     $tl = textlib_get_instance();
1678     if(!empty($info) && $tl->strlen($info)>255) {
1679         $info = $tl->substr($info,0,252).'...';
1680         debugging('Warning: logged very long info',DEBUG_DEVELOPER);
1681     }
1683     // If the 100 field size is changed, also need to alter print_log in course/lib.php
1684     if(!empty($url) && $tl->strlen($url)>100) {
1685         $url=$tl->substr($url,0,97).'...';
1686         debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
1687     }
1689     if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++;};
1691     $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
1692                  'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
1694     try {
1695         $DB->insert_record_raw('log', $log, false);
1696     } catch (dml_write_exception $e) {
1697         debugging('Error: Could not insert a new entry to the Moodle log', DEBUG_ALL);
1698         // MDL-11893, alert $CFG->supportemail if insert into log failed
1699         if ($CFG->supportemail and empty($CFG->noemailever)) {
1700             // email_to_user is not usable because email_to_user tries to write to the logs table,
1701             // and this will get caught in an infinite loop, if disk is full
1702             $site = get_site();
1703             $subject = 'Insert into log failed at your moodle site '.$site->fullname;
1704             $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";
1705             $message .= "The failed query parameters are:\n\n" . var_export($log, true);
1707             $lasttime = get_config('admin', 'lastloginserterrormail');
1708             if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
1709                 //using email directly rather than messaging as they may not be able to log in to access a message
1710                 mail($CFG->supportemail, $subject, $message);
1711                 set_config('lastloginserterrormail', time(), 'admin');
1712             }
1713         }
1714     }
1717 /**
1718  * Store user last access times - called when use enters a course or site
1719  *
1720  * @global object
1721  * @global object
1722  * @global object
1723  * @uses LASTACCESS_UPDATE_SECS
1724  * @uses SITEID
1725  * @param int $courseid, empty means site
1726  * @return void
1727  */
1728 function user_accesstime_log($courseid=0) {
1729     global $USER, $CFG, $DB;
1731     if (!isloggedin() or session_is_loggedinas()) {
1732         // no access tracking
1733         return;
1734     }
1736     if (empty($courseid)) {
1737         $courseid = SITEID;
1738     }
1740     $timenow = time();
1742 /// Store site lastaccess time for the current user
1743     if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1744     /// Update $USER->lastaccess for next checks
1745         $USER->lastaccess = $timenow;
1747         $last = new stdClass();
1748         $last->id         = $USER->id;
1749         $last->lastip     = getremoteaddr();
1750         $last->lastaccess = $timenow;
1752         $DB->update_record_raw('user', $last);
1753     }
1755     if ($courseid == SITEID) {
1756     ///  no user_lastaccess for frontpage
1757         return;
1758     }
1760 /// Store course lastaccess times for the current user
1761     if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
1763         $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
1765         if ($lastaccess === false) {
1766             // Update course lastaccess for next checks
1767             $USER->currentcourseaccess[$courseid] = $timenow;
1769             $last = new stdClass();
1770             $last->userid     = $USER->id;
1771             $last->courseid   = $courseid;
1772             $last->timeaccess = $timenow;
1773             $DB->insert_record_raw('user_lastaccess', $last, false);
1775         } else if ($timenow - $lastaccess <  LASTACCESS_UPDATE_SECS) {
1776             // no need to update now, it was updated recently in concurrent login ;-)
1778         } else {
1779             // Update course lastaccess for next checks
1780             $USER->currentcourseaccess[$courseid] = $timenow;
1782             $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
1783         }
1784     }
1787 /**
1788  * Select all log records based on SQL criteria
1789  *
1790  * @todo Finish documenting this function
1791  *
1792  * @global object
1793  * @param string $select SQL select criteria
1794  * @param array $params named sql type params
1795  * @param string $order SQL order by clause to sort the records returned
1796  * @param string $limitfrom ?
1797  * @param int $limitnum ?
1798  * @param int $totalcount Passed in by reference.
1799  * @return object
1800  */
1801 function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
1802     global $DB;
1804     if ($order) {
1805         $order = "ORDER BY $order";
1806     }
1808     $selectsql = "";
1809     $countsql  = "";
1811     if ($select) {
1812         $select = "WHERE $select";
1813     }
1815     $sql = "SELECT COUNT(*)
1816               FROM {log} l
1817            $select";
1819     $totalcount = $DB->count_records_sql($sql, $params);
1821     $sql = "SELECT l.*, u.firstname, u.lastname, u.picture
1822               FROM {log} l
1823               LEFT JOIN {user} u ON l.userid = u.id
1824            $select
1825             $order";
1827     return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
1831 /**
1832  * Select all log records for a given course and user
1833  *
1834  * @todo Finish documenting this function
1835  *
1836  * @global object
1837  * @uses DAYSECS
1838  * @param int $userid The id of the user as found in the 'user' table.
1839  * @param int $courseid The id of the course as found in the 'course' table.
1840  * @param string $coursestart ?
1841  */
1842 function get_logs_usercourse($userid, $courseid, $coursestart) {
1843     global $DB;
1845     $params = array();
1847     $courseselect = '';
1848     if ($courseid) {
1849         $courseselect = "AND course = :courseid";
1850         $params['courseid'] = $courseid;
1851     }
1852     $params['userid'] = $userid;
1853     $$coursestart = (int)$coursestart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1855     return $DB->get_records_sql("SELECT FLOOR((time - $coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
1856                                    FROM {log}
1857                                   WHERE userid = :userid
1858                                         AND time > $coursestart $courseselect
1859                                GROUP BY FLOOR((time - $coursestart)/". DAYSECS .")", $params);
1862 /**
1863  * Select all log records for a given course, user, and day
1864  *
1865  * @global object
1866  * @uses HOURSECS
1867  * @param int $userid The id of the user as found in the 'user' table.
1868  * @param int $courseid The id of the course as found in the 'course' table.
1869  * @param string $daystart ?
1870  * @return object
1871  */
1872 function get_logs_userday($userid, $courseid, $daystart) {
1873     global $DB;
1875     $params = array('userid'=>$userid);
1877     $courseselect = '';
1878     if ($courseid) {
1879         $courseselect = "AND course = :courseid";
1880         $params['courseid'] = $courseid;
1881     }
1882     $daystart = (int)$daystart; // note: unfortunately pg complains if you use name parameter or column alias in GROUP BY
1884     return $DB->get_records_sql("SELECT FLOOR((time - $daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
1885                                    FROM {log}
1886                                   WHERE userid = :userid
1887                                         AND time > $daystart $courseselect
1888                                GROUP BY FLOOR((time - $daystart)/". HOURSECS .") ", $params);
1891 /**
1892  * Returns an object with counts of failed login attempts
1893  *
1894  * Returns information about failed login attempts.  If the current user is
1895  * an admin, then two numbers are returned:  the number of attempts and the
1896  * number of accounts.  For non-admins, only the attempts on the given user
1897  * are shown.
1898  *
1899  * @global object
1900  * @uses CONTEXT_SYSTEM
1901  * @param string $mode Either 'admin' or 'everybody'
1902  * @param string $username The username we are searching for
1903  * @param string $lastlogin The date from which we are searching
1904  * @return int
1905  */
1906 function count_login_failures($mode, $username, $lastlogin) {
1907     global $DB;
1909     $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
1910     $select = "module='login' AND action='error' AND time > :lastlogin";
1912     $count = new stdClass();
1914     if (is_siteadmin()) {
1915         if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
1916             $count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
1917             return $count;
1918         }
1919     } else if ($mode == 'everybody') {
1920         if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
1921             return $count;
1922         }
1923     }
1924     return NULL;
1928 /// GENERAL HELPFUL THINGS  ///////////////////////////////////
1930 /**
1931  * Dump a given object's information in a PRE block.
1932  *
1933  * Mostly just used for debugging.
1934  *
1935  * @param mixed $object The data to be printed
1936  * @return void OUtput is echo'd
1937  */
1938 function print_object($object) {
1939     echo '<pre class="notifytiny">';
1940     print_r($object);  // Direct to output because some objects get too big for memory otherwise!
1941     echo '</pre>';
1944 /**
1945  * This function is the official hook inside XMLDB stuff to delegate its debug to one
1946  * external function.
1947  *
1948  * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1949  * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1950  *
1951  * @uses DEBUG_DEVELOPER
1952  * @param string $message string contains the error message
1953  * @param object $object object XMLDB object that fired the debug
1954  */
1955 function xmldb_debug($message, $object) {
1957     debugging($message, DEBUG_DEVELOPER);
1960 /**
1961  * @global object
1962  * @uses CONTEXT_COURSECAT
1963  * @return boolean Whether the user can create courses in any category in the system.
1964  */
1965 function user_can_create_courses() {
1966     global $DB;
1967     $catsrs = $DB->get_recordset('course_categories');
1968     foreach ($catsrs as $cat) {
1969         if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) {
1970             $catsrs->close();
1971             return true;
1972         }
1973     }
1974     $catsrs->close();
1975     return false;