weblib.php MDL-19236 added phpdocs and copyrights
[moodle.git] / lib / datalib.php
CommitLineData
6078ba30 1<?php // $Id$
341b5ed2 2
7cf1c7bd 3/**
4 * Library of functions for database manipulation.
5930cded 5 *
7cf1c7bd 6 * Other main libraries:
7 * - weblib.php - functions that produce web output
8 * - moodlelib.php - general-purpose Moodle functions
6159ce65 9 * @author Martin Dougiamas and many others
89dcb99d 10 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7cf1c7bd 11 * @package moodlecore
12 */
13
a1b892cc 14define('MAX_COURSES_IN_CATEGORY', 10000); // MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
0cbe8111 15define('MAX_COURSE_CATEGORIES', 10000);
16
341b5ed2 17 /// Some constants
18 define('LASTACCESS_UPDATE_SECS', 60); /// Number of seconds to wait before
19 /// updating lastaccess information in DB.
df28d6c5 20
df28d6c5 21/// USER DATABASE ////////////////////////////////////////////////
22
18a97fd8 23/**
fbc21ae8 24 * Returns $user object of the main admin user
20aeb4b8 25 * primary admin = admin with lowest role_assignment id among admins
fbc21ae8 26 * @uses $CFG
27 * @return object(admin) An associative array representing the admin user.
fbc21ae8 28 */
df28d6c5 29function get_admin () {
df28d6c5 30
31 global $CFG;
2965f8fd 32 static $myadmin;
33
34 if (isset($myadmin)) {
35 return $myadmin;
36 }
df28d6c5 37
38 if ( $admins = get_admins() ) {
39 foreach ($admins as $admin) {
2965f8fd 40 $myadmin = $admin;
8f0cd6ef 41 return $admin; // ie the first one
df28d6c5 42 }
43 } else {
44 return false;
45 }
46}
47
18a97fd8 48/**
c26ecb1a 49 * Returns list of all admins, using 1 DB query. It depends on DB schema v1.7
50 * but does not depend on the v1.9 datastructures (context.path, etc).
fbc21ae8 51 *
52 * @uses $CFG
7290c7fa 53 * @return object
fbc21ae8 54 */
df28d6c5 55function get_admins() {
624a690b 56 global $DB;
5930cded 57
c26ecb1a 58 $sql = "SELECT ra.userid, SUM(rc.permission) AS permission, MIN(ra.id) AS adminid
624a690b 59 FROM {role_capabilities} rc
60 JOIN {context} ctx ON ctx.id=rc.contextid
61 JOIN {role_assignments} ra ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
d251907c 62 WHERE ctx.contextlevel=10 AND rc.capability IN (?, ?, ?)
624a690b 63 GROUP BY ra.userid
c26ecb1a 64 HAVING SUM(rc.permission) > 0";
624a690b 65 $params = array('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything');
c26ecb1a 66
67 $sql = "SELECT u.*, ra.adminid
624a690b 68 FROM {user} u
69 JOIN ($sql) ra
70 ON u.id=ra.userid
71 ORDER BY ra.adminid ASC";
5930cded 72
624a690b 73 return $DB->get_records_sql($sql, $params);
df28d6c5 74}
75
76
b61efafb 77function get_courses_in_metacourse($metacourseid) {
624a690b 78 global $DB;
b61efafb 79
624a690b 80 $sql = "SELECT c.id, c.shortname, c.fullname
81 FROM {course} c, {course_meta} mc
82 WHERE mc.parent_course = ? AND mc.child_course = c.id
83 ORDER BY c.shortname";
84 $params = array($metacourseid);
b61efafb 85
624a690b 86 return $DB->get_records_sql($sql, $params);
b61efafb 87}
88
624a690b 89function get_courses_notin_metacourse($metacourseid) {
90 global $DB;
b61efafb 91
624a690b 92 if ($alreadycourses = get_courses_in_metacourse($metacourseid)) {
93 $alreadycourses = implode(',',array_keys($alreadycourses));
94 $alreadycourses = "AND c.id NOT IN ($alreadycourses)";
c44d5d42 95 } else {
624a690b 96 $alreadycourses = "";
b61efafb 97 }
178ccd11 98
624a690b 99 $sql = "SELECT c.id,c.shortname,c.fullname
100 FROM {course} c
101 WHERE c.id != ? and c.id != ".SITEID." and c.metacourse != 1
102 $alreadycourses
103 ORDER BY c.shortname";
104 $params = array($metacourseid);
5930cded 105
624a690b 106 return $DB->get_records_sql($sql, $params);
b61efafb 107}
108
493cde24 109function count_courses_notin_metacourse($metacourseid) {
624a690b 110 global $DB;
493cde24 111
624a690b 112 if ($alreadycourses = get_courses_in_metacourse($metacourseid)) {
113 $alreadycourses = implode(',',array_keys($alreadycourses));
114 $alreadycourses = "AND c.id NOT IN ($alreadycourses)";
115 } else {
116 $alreadycourses = "";
493cde24 117 }
118
d251907c 119 $sql = "SELECT COUNT(c.id)
624a690b 120 FROM {course} c
121 WHERE c.id != ? and c.id != ".SITEID." and c.metacourse != 1
122 $alreadycourses";
123 $params = array($metacourseid);
124
125 return $DB->count_records_sql($sql, $params);
493cde24 126}
127
900df8b6 128/**
fbc21ae8 129 * Search through course users
130 *
5930cded 131 * If $coursid specifies the site course then this function searches
fbc21ae8 132 * through all undeleted and confirmed users
133 *
fbc21ae8 134 * @param int $courseid The course in question.
135 * @param int $groupid The group in question.
136 * @param string $searchtext ?
137 * @param string $sort ?
624a690b 138 * @param array $exceptions ?
7290c7fa 139 * @return object
fbc21ae8 140 */
624a690b 141function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
142 global $DB;
0720313b 143
245ac557 144 $LIKE = $DB->sql_ilike();
145 $fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
8f0cd6ef 146
900df8b6 147 if (!empty($exceptions)) {
624a690b 148 list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex0000', false);
149 $except = "AND u.id $exceptions";
900df8b6 150 } else {
624a690b 151 $except = "";
152 $params = array();
900df8b6 153 }
2700d113 154
900df8b6 155 if (!empty($sort)) {
624a690b 156 $order = "ORDER BY $sort";
900df8b6 157 } else {
624a690b 158 $order = "";
900df8b6 159 }
8f0cd6ef 160
624a690b 161 $select = "u.deleted = 0 AND u.confirmed = 1 AND ($fullname $LIKE :search1 OR u.email $LIKE :search2)";
162 $params['search1'] = "%$searchtext%";
163 $params['search2'] = "%$searchtext%";
2700d113 164
222ac91b 165 if (!$courseid or $courseid == SITEID) {
624a690b 166 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
167 FROM {user} u
168 WHERE $select
169 $except
170 $order";
171 return $DB->get_records_sql($sql, $params);
2700d113 172
624a690b 173 } else {
900df8b6 174 if ($groupid) {
624a690b 175 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
176 FROM {user} u
177 JOIN {groups_members} gm ON gm.userid = u.id
178 WHERE $select AND gm.groupid = :groupid
179 $except
180 $order";
181 $params['groupid'] = $groupid;
182 return $DB->get_records_sql($sql, $params);
183
900df8b6 184 } else {
ea8158c1 185 $context = get_context_instance(CONTEXT_COURSE, $courseid);
186 $contextlists = get_related_contexts_string($context);
624a690b 187
188 $sql = "SELECT u.id, u.firstname, u.lastname, u.email
189 FROM {user} u
190 JOIN {role_assignments} ra ON ra.userid = u.id
191 WHERE $select AND ra.contextid $contextlists
192 $except
193 $order";
194 return $DB->get_records_sql($sql, $params);
900df8b6 195 }
196 }
df28d6c5 197}
198
18a97fd8 199/**
fbc21ae8 200 * Returns a subset of users
201 *
202 * @uses $CFG
7290c7fa 203 * @param bool $get If false then only a count of the records is returned
fbc21ae8 204 * @param string $search A simple string to search for
7290c7fa 205 * @param bool $confirmed A switch to allow/disallow unconfirmed users
fbc21ae8 206 * @param array(int) $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
207 * @param string $sort A SQL snippet for the sorting criteria to use
208 * @param string $firstinitial ?
209 * @param string $lastinitial ?
210 * @param string $page ?
211 * @param string $recordsperpage ?
212 * @param string $fields A comma separated list of fields to be returned from the chosen table.
7290c7fa 213 * @return object|false|int {@link $USER} records unless get is false in which case the integer count of the records found is returned. False is returned if an error is encountered.
fbc21ae8 214 */
624a690b 215function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
216 $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
217 global $DB;
5930cded 218
36075e09 219 if ($get && !$recordsperpage) {
220 debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
221 'On large installations, this will probably cause an out of memory error. ' .
222 'Please think again and change your code so that it does not try to ' .
03517306 223 'load so much data into memory.', DEBUG_DEVELOPER);
36075e09 224 }
18a97fd8 225
245ac557 226 $LIKE = $DB->sql_ilike();
227 $fullname = $DB->sql_fullname();
e384fb7b 228
624a690b 229 $select = " username <> :guest AND deleted = 0";
230 $params = array('guest'=>'guest');
488acd1b 231
0044147e 232 if (!empty($search)){
233 $search = trim($search);
624a690b 234 $select .= " AND ($fullname $LIKE :search1 OR email $LIKE :search2 OR username = :search3)";
235 $params['search1'] = "%$search%";
236 $params['search2'] = "%$search%";
237 $params['search3'] = "$search";
e384fb7b 238 }
239
5a741655 240 if ($confirmed) {
624a690b 241 $select .= " AND confirmed = 1";
5a741655 242 }
243
244 if ($exceptions) {
624a690b 245 list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex0000', false);
246 $params = $params + $eparams;
247 $except = " AND id $exceptions";
5a741655 248 }
249
488acd1b 250 if ($firstinitial) {
624a690b 251 $select .= " AND firstname $LIKE :fni";
252 $params['fni'] = "$firstinitial%";
8f0cd6ef 253 }
488acd1b 254 if ($lastinitial) {
624a690b 255 $select .= " AND lastname $LIKE :lni";
256 $params['lni'] = "$lastinitial%";
8f0cd6ef 257 }
488acd1b 258
cd1edf9e 259 if ($extraselect) {
624a690b 260 $select .= " AND $extraselect";
261 $params = $params + (array)$extraparams;
cd1edf9e 262 }
263
5a741655 264 if ($get) {
624a690b 265 return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
5a741655 266 } else {
624a690b 267 return $DB->count_records_select('user', $select, $params);
5a741655 268 }
9fa49e22 269}
270
5a741655 271
18a97fd8 272/**
fbc21ae8 273 * shortdesc (optional)
274 *
275 * longdesc
276 *
fbc21ae8 277 * @param string $sort ?
278 * @param string $dir ?
279 * @param int $categoryid ?
280 * @param int $categoryid ?
281 * @param string $search ?
282 * @param string $firstinitial ?
283 * @param string $lastinitial ?
7290c7fa 284 * @returnobject {@link $USER} records
fbc21ae8 285 * @todo Finish documenting this function
286 */
287
36075e09 288function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
624a690b 289 $search='', $firstinitial='', $lastinitial='', $extraselect='', array $extraparams=null) {
290 global $DB;
31fefa63 291
245ac557 292 $LIKE = $DB->sql_ilike();
293 $fullname = $DB->sql_fullname();
c2a96d6b 294
624a690b 295 $select = "deleted <> 1";
296 $params = array();
488acd1b 297
0044147e 298 if (!empty($search)) {
299 $search = trim($search);
624a690b 300 $select .= " AND ($fullname $LIKE :search1 OR email $LIKE :search2 OR username = :search3)";
301 $params['search1'] = "%$search%";
302 $params['search2'] = "%$search%";
303 $params['search3'] = "$search";
488acd1b 304 }
305
306 if ($firstinitial) {
624a690b 307 $select .= " AND firstname $LIKE :fni";
308 $params['fni'] = "$firstinitial%";
488acd1b 309 }
488acd1b 310 if ($lastinitial) {
624a690b 311 $select .= " AND lastname $LIKE :lni";
312 $params['lni'] = "$lastinitial%";
c750592a 313 }
314
cd1edf9e 315 if ($extraselect) {
624a690b 316 $select .= " AND $extraselect";
317 $params = $params + (array)$extraparams;
cd1edf9e 318 }
03d820c7 319
488acd1b 320 if ($sort) {
624a690b 321 $sort = " ORDER BY $sort $dir";
488acd1b 322 }
323
324/// warning: will return UNCONFIRMED USERS
624a690b 325 return $DB->get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
326 FROM {user}
327 WHERE $select
328 $sort", $params, $page, $recordsperpage);
9fa49e22 329
330}
331
488acd1b 332
18a97fd8 333/**
7290c7fa 334 * Full list of users that have confirmed their accounts.
fbc21ae8 335 *
624a690b 336 * @return array of unconfirmed users
fbc21ae8 337 */
9fa49e22 338function get_users_confirmed() {
624a690b 339 global $DB;
340 return $DB->get_records_sql("SELECT *
341 FROM {user}
342 WHERE confirmed = 1 AND deleted = 0 AND username <> ?", array('guest'));
9fa49e22 343}
344
345
02ebf404 346/// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
347
348
18a97fd8 349/**
fbc21ae8 350 * Returns $course object of the top-level site.
351 *
89dcb99d 352 * @return course A {@link $COURSE} object for the site
fbc21ae8 353 */
c44d5d42 354function get_site() {
624a690b 355 global $SITE, $DB;
c44d5d42 356
357 if (!empty($SITE->id)) { // We already have a global to use, so return that
358 return $SITE;
359 }
02ebf404 360
624a690b 361 if ($course = $DB->get_record('course', array('category'=>0))) {
02ebf404 362 return $course;
363 } else {
364 return false;
365 }
366}
367
18a97fd8 368/**
613bbd7c 369 * Returns list of courses, for whole site, or category
370 *
371 * Returns list of courses, for whole site, or category
bfbfdb53 372 * Important: Using c.* for fields is extremely expensive because
613bbd7c 373 * we are using distinct. You almost _NEVER_ need all the fields
374 * in such a large SELECT
375 *
376 * @param type description
3b8a284c 377 * @return array of courses
613bbd7c 378 */
6315b1c8 379function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
02ebf404 380
3b8a284c 381 global $USER, $CFG, $DB;
5930cded 382
3b8a284c 383 $params = array();
384
385 if ($categoryid !== "all" && is_numeric($categoryid)) {
386 $categoryselect = "WHERE c.category = :catid";
387 $params['catid'] = $categoryid;
71dea306 388 } else {
5930cded 389 $categoryselect = "";
09575480 390 }
391
392 if (empty($sort)) {
393 $sortstatement = "";
394 } else {
395 $sortstatement = "ORDER BY $sort";
396 }
397
398 $visiblecourses = array();
5930cded 399
3b8a284c 400 $sql = "SELECT $fields,
401 ctx.id AS ctxid, ctx.path AS ctxpath,
402 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
403 FROM {course} c
404 JOIN {context} ctx
405 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
406 $categoryselect
407 $sortstatement";
408
71dea306 409 // pull out all course matching the cat
3b8a284c 410 if ($courses = $DB->get_records_sql($sql, $params)) {
09575480 411
412 // loop throught them
413 foreach ($courses as $course) {
656418b1 414 $course = make_context_subobj($course);
285f94f5 415 if (isset($course->visible) && $course->visible <= 0) {
09575480 416 // for hidden courses, require visibility check
656418b1 417 if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
3b8a284c 418 $visiblecourses [$course->id] = $course;
09575480 419 }
420 } else {
3b8a284c 421 $visiblecourses [$course->id] = $course;
5930cded 422 }
09575480 423 }
6315b1c8 424 }
71dea306 425 return $visiblecourses;
8130b77b 426}
427
8130b77b 428
6315b1c8 429/**
613bbd7c 430 * Returns list of courses, for whole site, or category
431 *
432 * Similar to get_courses, but allows paging
5930cded 433 * Important: Using c.* for fields is extremely expensive because
613bbd7c 434 * we are using distinct. You almost _NEVER_ need all the fields
435 * in such a large SELECT
436 *
437 * @param type description
3b8a284c 438 * @return array of courses
613bbd7c 439 */
6315b1c8 440function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
441 &$totalcount, $limitfrom="", $limitnum="") {
3b8a284c 442 global $USER, $CFG, $DB;
c7fe5c6f 443
3b8a284c 444 $params = array();
5930cded 445
71dea306 446 $categoryselect = "";
447 if ($categoryid != "all" && is_numeric($categoryid)) {
3b8a284c 448 $categoryselect = "WHERE c.category = :catid";
449 $params['catid'] = $categoryid;
71dea306 450 } else {
5930cded 451 $categoryselect = "";
452 }
453
3b8a284c 454 $sql = "SELECT $fields,
455 ctx.id AS ctxid, ctx.path AS ctxpath,
456 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
457 FROM {course} c
458 JOIN {context} ctx
459 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
460 $categoryselect
461 ORDER BY $sort";
462
71dea306 463 // pull out all course matching the cat
3b8a284c 464 if (!$rs = $DB->get_recordset_sql($sql, $params)) {
465 return array();
12490fc2 466 }
71dea306 467 $totalcount = 0;
5930cded 468
285f94f5 469 if (!$limitfrom) {
5930cded 470 $limitfrom = 0;
71dea306 471 }
5930cded 472
71dea306 473 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
3b8a284c 474 $visiblecourses = array();
475 foreach($rs as $course) {
03cedd62 476 $course = make_context_subobj($course);
477 if ($course->visible <= 0) {
478 // for hidden courses, require visibility check
479 if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
71dea306 480 $totalcount++;
03cedd62 481 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
3b8a284c 482 $visiblecourses [$course->id] = $course;
71dea306 483 }
484 }
03cedd62 485 } else {
486 $totalcount++;
487 if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
3b8a284c 488 $visiblecourses [$course->id] = $course;
03cedd62 489 }
5930cded 490 }
71dea306 491 }
3b8a284c 492 $rs->close();
71dea306 493 return $visiblecourses;
02ebf404 494}
495
624a690b 496/**
70f15878 497 * Retrieve course records with the course managers and other related records
498 * that we need for print_course(). This allows print_courses() to do its job
499 * in a constant number of DB queries, regardless of the number of courses,
500 * role assignments, etc.
bfbfdb53 501 *
70f15878 502 * The returned array is indexed on c.id, and each course will have
503 * - $course->context - a context obj
504 * - $course->managers - array containing RA objects that include a $user obj
505 * with the minimal fields needed for fullname()
506 *
507 */
508function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
509 /*
bfbfdb53 510 * The plan is to
70f15878 511 *
512 * - Grab the courses JOINed w/context
513 *
514 * - Grab the interesting course-manager RAs
515 * JOINed with a base user obj and add them to each course
516 *
517 * So as to do all the work in 2 DB queries. The RA+user JOIN
518 * ends up being pretty expensive if it happens over _all_
519 * courses on a large site. (Are we surprised!?)
520 *
521 * So this should _never_ get called with 'all' on a large site.
522 *
523 */
3b8a284c 524 global $USER, $CFG, $DB;
70f15878 525
3b8a284c 526 $params = array();
70f15878 527 $allcats = false; // bool flag
528 if ($categoryid === 'all') {
529 $categoryclause = '';
530 $allcats = true;
531 } elseif (is_numeric($categoryid)) {
3b8a284c 532 $categoryclause = "c.category = :catid";
533 $params['catid'] = $categoryid;
70f15878 534 } else {
535 debugging("Could not recognise categoryid = $categoryid");
536 $categoryclause = '';
537 }
538
539 $basefields = array('id', 'category', 'sortorder',
540 'shortname', 'fullname', 'idnumber',
70f15878 541 'guest', 'startdate', 'visible',
542 'newsitems', 'cost', 'enrol',
543 'groupmode', 'groupmodeforce');
544
545 if (!is_null($fields) && is_string($fields)) {
546 if (empty($fields)) {
547 $fields = $basefields;
548 } else {
bfbfdb53 549 // turn the fields from a string to an array that
70f15878 550 // get_user_courses_bycap() will like...
551 $fields = explode(',',$fields);
552 $fields = array_map('trim', $fields);
553 $fields = array_unique(array_merge($basefields, $fields));
554 }
555 } elseif (is_array($fields)) {
556 $fields = array_merge($basefields,$fields);
557 }
558 $coursefields = 'c.' .join(',c.', $fields);
559
560 if (empty($sort)) {
561 $sortstatement = "";
562 } else {
563 $sortstatement = "ORDER BY $sort";
564 }
565
e89f157b 566 $where = 'WHERE c.id != ' . SITEID;
70f15878 567 if ($categoryclause !== ''){
e89f157b 568 $where = "$where AND $categoryclause";
70f15878 569 }
570
571 // pull out all courses matching the cat
572 $sql = "SELECT $coursefields,
45ea1afb 573 ctx.id AS ctxid, ctx.path AS ctxpath,
574 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
3b8a284c 575 FROM {course} c
576 JOIN {context} ctx
577 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
578 $where
579 $sortstatement";
70f15878 580
581 $catpaths = array();
582 $catpath = NULL;
3b8a284c 583 if ($courses = $DB->get_records_sql($sql, $params)) {
70f15878 584 // loop on courses materialising
bfbfdb53 585 // the context, and prepping data to fetch the
70f15878 586 // managers efficiently later...
587 foreach ($courses as $k => $course) {
588 $courses[$k] = make_context_subobj($courses[$k]);
589 $courses[$k]->managers = array();
590 if ($allcats === false) {
591 // single cat, so take just the first one...
592 if ($catpath === NULL) {
593 $catpath = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
594 }
595 } else {
596 // chop off the contextid of the course itself
597 // like dirname() does...
598 $catpaths[] = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
599 }
600 }
601 } else {
602 return array(); // no courses!
603 }
604
b1cff118 605 $CFG->coursemanager = trim($CFG->coursemanager);
606 if (empty($CFG->coursemanager)) {
607 return $courses;
608 }
609
70f15878 610 $managerroles = split(',', $CFG->coursemanager);
611 $catctxids = '';
612 if (count($managerroles)) {
613 if ($allcats === true) {
614 $catpaths = array_unique($catpaths);
615 $ctxids = array();
616 foreach ($catpaths as $cpath) {
617 $ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
618 }
619 $ctxids = array_unique($ctxids);
620 $catctxids = implode( ',' , $ctxids);
c7a71127 621 unset($catpaths);
622 unset($cpath);
70f15878 623 } else {
624 // take the ctx path from the first course
625 // as all categories will be the same...
626 $catpath = substr($catpath,1);
627 $catpath = preg_replace(':/\d+$:','',$catpath);
628 $catctxids = str_replace('/',',',$catpath);
629 }
630 if ($categoryclause !== '') {
631 $categoryclause = "AND $categoryclause";
632 }
633 /*
bfbfdb53 634 * Note: Here we use a LEFT OUTER JOIN that can
70f15878 635 * "optionally" match to avoid passing a ton of context
636 * ids in an IN() clause. Perhaps a subselect is faster.
637 *
638 * In any case, this SQL is not-so-nice over large sets of
639 * courses with no $categoryclause.
640 *
641 */
642 $sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
bfbfdb53 643 ra.hidden,
70f15878 644 r.id AS roleid, r.name as rolename,
645 u.id AS userid, u.firstname, u.lastname
3b8a284c 646 FROM {role_assignments} ra
647 JOIN {context} ctx ON ra.contextid = ctx.id
648 JOIN {user} u ON ra.userid = u.id
649 JOIN {role} r ON ra.roleid = r.id
650 LEFT OUTER JOIN {course} c
651 ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
c7a71127 652 WHERE ( c.id IS NOT NULL";
653 // under certain conditions, $catctxids is NULL
654 if($catctxids == NULL){
655 $sql .= ") ";
656 }else{
657 $sql .= " OR ra.contextid IN ($catctxids) )";
658 }
659
660 $sql .= "AND ra.roleid IN ({$CFG->coursemanager})
70f15878 661 $categoryclause
662 ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
3b8a284c 663 $rs = $DB->get_recordset_sql($sql, $params);
bfbfdb53 664
70f15878 665 // This loop is fairly stupid as it stands - might get better
666 // results doing an initial pass clustering RAs by path.
3b8a284c 667 foreach($rs as $ra) {
03cedd62 668 $user = new StdClass;
669 $user->id = $ra->userid; unset($ra->userid);
670 $user->firstname = $ra->firstname; unset($ra->firstname);
671 $user->lastname = $ra->lastname; unset($ra->lastname);
672 $ra->user = $user;
673 if ($ra->contextlevel == CONTEXT_SYSTEM) {
674 foreach ($courses as $k => $course) {
675 $courses[$k]->managers[] = $ra;
676 }
677 } elseif ($ra->contextlevel == CONTEXT_COURSECAT) {
678 if ($allcats === false) {
679 // It always applies
70f15878 680 foreach ($courses as $k => $course) {
681 $courses[$k]->managers[] = $ra;
682 }
03cedd62 683 } else {
684 foreach ($courses as $k => $course) {
685 // Note that strpos() returns 0 as "matched at pos 0"
686 if (strpos($course->context->path, $ra->path.'/')===0) {
687 // Only add it to subpaths
70f15878 688 $courses[$k]->managers[] = $ra;
689 }
70f15878 690 }
70f15878 691 }
03cedd62 692 } else { // course-level
693 if(!array_key_exists($ra->instanceid, $courses)) {
694 //this course is not in a list, probably a frontpage course
695 continue;
696 }
697 $courses[$ra->instanceid]->managers[] = $ra;
70f15878 698 }
699 }
3b8a284c 700 $rs->close();
70f15878 701 }
702
703 return $courses;
704}
02ebf404 705
18a97fd8 706/**
bfbfdb53 707 * Convenience function - lists courses that a user has access to view.
fbc21ae8 708 *
82c62d1b 709 * For admins and others with access to "every" course in the system, we should
710 * try to get courses with explicit RAs.
711 *
712 * NOTE: this function is heavily geared towards the perspective of the user
bfbfdb53 713 * passed in $userid. So it will hide courses that the user cannot see
82c62d1b 714 * (for any reason) even if called from cron or from another $USER's
715 * perspective.
bfbfdb53 716 *
82c62d1b 717 * If you really want to know what courses are assigned to the user,
bfbfdb53 718 * without any hiding or scheming, call the lower-level
82c62d1b 719 * get_user_courses_bycap().
720 *
721 *
722 * Notes inherited from get_user_courses_bycap():
e1d5e5c1 723 *
724 * - $fields is an array of fieldnames to ADD
725 * so name the fields you really need, which will
726 * be added and uniq'd
727 *
728 * - the course records have $c->context which is a fully
729 * valid context object. Saves you a query per course!
730 *
352f6f74 731 * @uses $CFG,$USER
7290c7fa 732 * @param int $userid The user of interest
33f85740 733 * @param string $sort the sortorder in the course table
e1d5e5c1 734 * @param array $fields - names of _additional_ fields to return (also accepts a string)
f8e1c7af 735 * @param bool $doanything True if using the doanything flag
736 * @param int $limit Maximum number of records to return, or 0 for unlimited
33f85740 737 * @return array {@link $COURSE} of course objects
fbc21ae8 738 */
e1d5e5c1 739function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
3b8a284c 740 global $CFG, $USER, $DB;
5930cded 741
4dbca99e 742 // Guest's do not have any courses
12d06877 743 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
3b8a284c 744 if (has_capability('moodle/legacy:guest', $sitecontext, $userid, false)) {
4dbca99e 745 return(array());
746 }
601edb90 747
352f6f74 748 $basefields = array('id', 'category', 'sortorder',
749 'shortname', 'fullname', 'idnumber',
352f6f74 750 'guest', 'startdate', 'visible',
751 'newsitems', 'cost', 'enrol',
752 'groupmode', 'groupmodeforce');
753
e1d5e5c1 754 if (!is_null($fields) && is_string($fields)) {
755 if (empty($fields)) {
352f6f74 756 $fields = $basefields;
e1d5e5c1 757 } else {
bfbfdb53 758 // turn the fields from a string to an array that
573674bf 759 // get_user_courses_bycap() will like...
352f6f74 760 $fields = explode(',',$fields);
761 $fields = array_map('trim', $fields);
762 $fields = array_unique(array_merge($basefields, $fields));
763 }
bbfed0ec 764 } elseif (is_array($fields)) {
bfbfdb53 765 $fields = array_unique(array_merge($basefields, $fields));
352f6f74 766 } else {
767 $fields = $basefields;
768 }
769
b9e9491a 770 $orderby = '';
771 $sort = trim($sort);
772 if (!empty($sort)) {
70070493 773 $rawsorts = explode(',', $sort);
774 $sorts = array();
775 foreach ($rawsorts as $rawsort) {
776 $rawsort = trim($rawsort);
c7e6b7e4 777 if (strpos($rawsort, 'c.') === 0) {
70070493 778 $rawsort = substr($rawsort, 2);
779 }
780 $sorts[] = trim($rawsort);
781 }
782 $sort = 'c.'.implode(',c.', $sorts);
b9e9491a 783 $orderby = "ORDER BY $sort";
784 }
785
352f6f74 786 //
787 // Logged-in user - Check cached courses
788 //
789 // NOTE! it's a _string_ because
790 // - it's all we'll ever use
791 // - it serialises much more compact than an array
82c62d1b 792 // this a big concern here - cost of serialise
793 // and unserialise gets huge as the session grows
352f6f74 794 //
795 // If the courses are too many - it won't be set
796 // for large numbers of courses, caching in the session
797 // has marginal benefits (costs too much, not
798 // worthwhile...) and we may hit SQL parser limits
799 // because we use IN()
800 //
ae1555ae 801 if ($userid === $USER->id) {
bfbfdb53 802 if (isset($USER->loginascontext)
fe3141e0 803 && $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
ae1555ae 804 // list _only_ this course
805 // anything else is asking for trouble...
806 $courseids = $USER->loginascontext->instanceid;
bfbfdb53 807 } elseif (isset($USER->mycourses)
ae1555ae 808 && is_string($USER->mycourses)) {
809 if ($USER->mycourses === '') {
810 // empty str means: user has no courses
811 // ... so do the easy thing...
812 return array();
813 } else {
814 $courseids = $USER->mycourses;
815 }
816 }
817 if (isset($courseids)) {
bfbfdb53 818 // The data massaging here MUST be kept in sync with
352f6f74 819 // get_user_courses_bycap() so we return
820 // the same...
821 // (but here we don't need to check has_cap)
822 $coursefields = 'c.' .join(',c.', $fields);
823 $sql = "SELECT $coursefields,
45ea1afb 824 ctx.id AS ctxid, ctx.path AS ctxpath,
825 ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel,
82c62d1b 826 cc.path AS categorypath
3b8a284c 827 FROM {course} c
828 JOIN {course_categories} cc ON c.category=cc.id
829 JOIN {context} ctx
830 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
831 WHERE c.id IN ($courseids)
832 $orderby";
833 $rs = $DB->get_recordset_sql($sql);
352f6f74 834 $courses = array();
835 $cc = 0; // keep count
3b8a284c 836 foreach ($rs as $c) {
03cedd62 837 // build the context obj
838 $c = make_context_subobj($c);
c1b7a5e5 839
03cedd62 840 $courses[$c->id] = $c;
841 if ($limit > 0 && $cc++ > $limit) {
842 break;
352f6f74 843 }
844 }
3b8a284c 845 $rs->close();
352f6f74 846 return $courses;
2f3499b7 847 }
848 }
152a9060 849
352f6f74 850 // Non-cached - get accessinfo
e1d5e5c1 851 if ($userid === $USER->id && isset($USER->access)) {
aeb3916b 852 $accessinfo = $USER->access;
bdf3bbd1 853 } else {
e1d5e5c1 854 $accessinfo = get_user_access_sitewide($userid);
aeb3916b 855 }
352f6f74 856
bfbfdb53 857
573674bf 858 $courses = get_user_courses_bycap($userid, 'moodle/course:view', $accessinfo,
859 $doanything, $sort, $fields,
860 $limit);
352f6f74 861
82c62d1b 862 $cats = NULL;
863 // If we have to walk category visibility
864 // to eval course visibility, get the categories
865 if (empty($CFG->allowvisiblecoursesinhiddencategories)) {
866 $sql = "SELECT cc.id, cc.path, cc.visible,
45ea1afb 867 ctx.id AS ctxid, ctx.path AS ctxpath,
868 ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel
3b8a284c 869 FROM {course_categories} cc
870 JOIN {context} ctx ON (cc.id = ctx.instanceid)
871 WHERE ctx.contextlevel = ".CONTEXT_COURSECAT."
872 ORDER BY cc.id";
873 $rs = $DB->get_recordset_sql($sql);
bfbfdb53 874
875 // Using a temporary array instead of $cats here, to avoid a "true" result when isnull($cats) further down
876 $categories = array();
3b8a284c 877 foreach($rs as $course_cat) {
03cedd62 878 // build the context obj
879 $course_cat = make_context_subobj($course_cat);
880 $categories[$course_cat->id] = $course_cat;
82c62d1b 881 }
3b8a284c 882 $rs->close();
bfbfdb53 883
884 if (!empty($categories)) {
885 $cats = $categories;
886 }
887
888 unset($course_cat);
82c62d1b 889 }
352f6f74 890 //
891 // Strangely, get_my_courses() is expected to return the
aeb3916b 892 // array keyed on id, which messes up the sorting
352f6f74 893 // So do that, and also cache the ids in the session if appropriate
894 //
aeb3916b 895 $kcourses = array();
bfbfdb53 896 $courses_count = count($courses);
352f6f74 897 $cacheids = NULL;
82c62d1b 898 $vcatpaths = array();
bfbfdb53 899 if ($userid === $USER->id && $courses_count < 500) {
352f6f74 900 $cacheids = array();
901 }
bfbfdb53 902 for ($n=0; $n<$courses_count; $n++) {
82c62d1b 903
904 //
b00cb46b 905 // Check whether $USER (not $userid) can _actually_ see them
82c62d1b 906 // Easy if $CFG->allowvisiblecoursesinhiddencategories
907 // is set, and we don't have to care about categories.
908 // Lots of work otherwise... (all in mem though!)
909 //
bfbfdb53 910 $cansee = false;
82c62d1b 911 if (is_null($cats)) { // easy rules!
912 if ($courses[$n]->visible == true) {
913 $cansee = true;
914 } elseif (has_capability('moodle/course:viewhiddencourses',
b00cb46b 915 $courses[$n]->context, $USER->id)) {
82c62d1b 916 $cansee = true;
917 }
918 } else {
919 //
920 // Is the cat visible?
921 // we have to assume it _is_ visible
922 // so we can shortcut when we find a hidden one
923 //
924 $viscat = true;
925 $cpath = $courses[$n]->categorypath;
926 if (isset($vcatpaths[$cpath])) {
927 $viscat = $vcatpaths[$cpath];
928 } else {
929 $cpath = substr($cpath,1); // kill leading slash
930 $cpath = explode('/',$cpath);
931 $ccct = count($cpath);
932 for ($m=0;$m<$ccct;$m++) {
933 $ccid = $cpath[$m];
934 if ($cats[$ccid]->visible==false) {
935 $viscat = false;
936 break;
937 }
938 }
939 $vcatpaths[$courses[$n]->categorypath] = $viscat;
940 }
941
942 //
b00cb46b 943 // Perhaps it's actually visible to $USER
8ed5dd63 944 // check moodle/category:viewhiddencategories
bfbfdb53 945 //
82c62d1b 946 // The name isn't obvious, but the description says
947 // "See hidden categories" so the user shall see...
bfbfdb53 948 // But also check if the allowvisiblecoursesinhiddencategories setting is true, and check for course visibility
82c62d1b 949 if ($viscat === false) {
bfbfdb53 950 $catctx = $cats[$courses[$n]->category]->context;
8ed5dd63 951 if (has_capability('moodle/category:viewhiddencategories', $catctx, $USER->id)) {
82c62d1b 952 $vcatpaths[$courses[$n]->categorypath] = true;
953 $viscat = true;
bfbfdb53 954 } elseif ($CFG->allowvisiblecoursesinhiddencategories && $courses[$n]->visible == true) {
955 $viscat = true;
82c62d1b 956 }
957 }
958
959 //
960 // Decision matrix
961 //
962 if ($viscat === true) {
963 if ($courses[$n]->visible == true) {
964 $cansee = true;
965 } elseif (has_capability('moodle/course:viewhiddencourses',
b00cb46b 966 $courses[$n]->context, $USER->id)) {
82c62d1b 967 $cansee = true;
968 }
969 }
970 }
971 if ($cansee === true) {
972 $kcourses[$courses[$n]->id] = $courses[$n];
973 if (is_array($cacheids)) {
974 $cacheids[] = $courses[$n]->id;
975 }
352f6f74 976 }
977 }
978 if (is_array($cacheids)) {
979 // Only happens
980 // - for the logged in user
981 // - below the threshold (500)
982 // empty string is _valid_
983 $USER->mycourses = join(',',$cacheids);
984 } elseif ($userid === $USER->id && isset($USER->mycourses)) {
985 // cheap sanity check
986 unset($USER->mycourses);
aeb3916b 987 }
352f6f74 988
aeb3916b 989 return $kcourses;
02ebf404 990}
991
18a97fd8 992/**
7290c7fa 993 * A list of courses that match a search
fbc21ae8 994 *
995 * @uses $CFG
996 * @param array $searchterms ?
997 * @param string $sort ?
998 * @param int $page ?
999 * @param int $recordsperpage ?
1000 * @param int $totalcount Passed in by reference. ?
7290c7fa 1001 * @return object {@link $COURSE} records
fbc21ae8 1002 */
d4419d55 1003function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
3b8a284c 1004 global $CFG, $DB;
02ebf404 1005
06c1a1da 1006 if ($DB->sql_regex_supported()) {
1007 $REGEXP = $DB->sql_regex(true);
1008 $NOTREGEXP = $DB->sql_regex(false);
02ebf404 1009 }
3b8a284c 1010 $LIKE = $DB->sql_ilike(); // case-insensitive
02ebf404 1011
06c1a1da 1012 $searchcond = array();
1013 $params = array();
1014 $i = 0;
02ebf404 1015
06c1a1da 1016 $concat = $DB->sql_concat('c.summary', "' '", 'c.fullname');
3b8a284c 1017
02ebf404 1018 foreach ($searchterms as $searchterm) {
06c1a1da 1019 $i++;
6bb0f67f 1020
0f62a5b5 1021 $NOT = ''; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
1022 /// will use it to simulate the "-" operator with LIKE clause
1023
6bb0f67f 1024 /// Under Oracle and MSSQL, trim the + and - operators and perform
0f62a5b5 1025 /// simpler LIKE (or NOT LIKE) queries
06c1a1da 1026 if (!$DB->sql_regex_supported()) {
0f62a5b5 1027 if (substr($searchterm, 0, 1) == '-') {
1028 $NOT = ' NOT ';
1029 }
6bb0f67f 1030 $searchterm = trim($searchterm, '+-');
1031 }
1032
06c1a1da 1033 // TODO: +- may not work for non latin languages
3b8a284c 1034
d4419d55 1035 if (substr($searchterm,0,1) == '+') {
06c1a1da 1036 $searchterm = trim($searchterm, '+-');
1037 $searchterm = preg_quote($searchterm, '|');
1038 $searchcond[] = "$concat $REGEXP :ss$i";
1039 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1040
a8b56716 1041 } else if (substr($searchterm,0,1) == "-") {
06c1a1da 1042 $searchterm = trim($searchterm, '+-');
1043 $searchterm = preg_quote($searchterm, '|');
1044 $searchcond[] = "$concat $NOTREGEXP :ss$i";
1045 $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
1046
a8b56716 1047 } else {
06c1a1da 1048 $searchcond[] = "$concat $NOT $LIKE :ss$i";
1049 $params['ss'.$i] = "%$searchterm%";
a8b56716 1050 }
02ebf404 1051 }
1052
06c1a1da 1053 if (empty($searchcond)) {
1054 $totalcount = 0;
1055 return array();
1056 }
1057
1058 $searchcond = implode(" AND ", $searchcond);
1059
2c64f65c 1060 $sql = "SELECT c.*,
45ea1afb 1061 ctx.id AS ctxid, ctx.path AS ctxpath,
1062 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
3b8a284c 1063 FROM {course} c
1064 JOIN {context} ctx
1065 ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
06c1a1da 1066 WHERE $searchcond AND c.id <> ".SITEID."
1067 ORDER BY $sort";
2c64f65c 1068 $courses = array();
3b8a284c 1069 $c = 0; // counts how many visible courses we've seen
02ebf404 1070
3b8a284c 1071 if ($rs = $DB->get_recordset_sql($sql, $params)) {
2c64f65c 1072 // Tiki pagination
1073 $limitfrom = $page * $recordsperpage;
1074 $limitto = $limitfrom + $recordsperpage;
2c64f65c 1075
3b8a284c 1076 foreach($rs as $course) {
2c64f65c 1077 $course = make_context_subobj($course);
1078 if ($course->visible || has_capability('moodle/course:viewhiddencourses', $course->context)) {
1079 // Don't exit this loop till the end
1080 // we need to count all the visible courses
1081 // to update $totalcount
1082 if ($c >= $limitfrom && $c < $limitto) {
3b8a284c 1083 $courses[$course->id] = $course;
02ebf404 1084 }
2c64f65c 1085 $c++;
02ebf404 1086 }
1087 }
3b8a284c 1088 $rs->close();
02ebf404 1089 }
1090
2c64f65c 1091 // our caller expects 2 bits of data - our return
1092 // array, and an updated $totalcount
1093 $totalcount = $c;
02ebf404 1094 return $courses;
1095}
1096
1097
18a97fd8 1098/**
40fb8aa6 1099 * Returns a sorted list of categories. Each category object has a context
1100 * property that is a context object.
bfbfdb53 1101 *
40fb8aa6 1102 * When asking for $parent='none' it will return all the categories, regardless
1103 * of depth. Wheen asking for a specific parent, the default is to return
1104 * a "shallow" resultset. Pass false to $shallow and it will return all
bfbfdb53 1105 * the child categories as well.
1106 *
fbc21ae8 1107 *
613bbd7c 1108 * @param string $parent The parent category if any
1109 * @param string $sort the sortorder
40fb8aa6 1110 * @param bool $shallow - set to false to get the children too
613bbd7c 1111 * @return array of categories
fbc21ae8 1112 */
40fb8aa6 1113function get_categories($parent='none', $sort=NULL, $shallow=true) {
3b8a284c 1114 global $DB;
40fb8aa6 1115
1116 if ($sort === NULL) {
1117 $sort = 'ORDER BY cc.sortorder ASC';
1118 } elseif ($sort ==='') {
1119 // leave it as empty
1120 } else {
1121 $sort = "ORDER BY $sort";
1122 }
02ebf404 1123
814748c9 1124 if ($parent === 'none') {
40fb8aa6 1125 $sql = "SELECT cc.*,
3b8a284c 1126 ctx.id AS ctxid, ctx.path AS ctxpath,
1127 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1128 FROM {course_categories} cc
1129 JOIN {context} ctx
1130 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
40fb8aa6 1131 $sort";
3b8a284c 1132 $params = array();
1133
40fb8aa6 1134 } elseif ($shallow) {
40fb8aa6 1135 $sql = "SELECT cc.*,
45ea1afb 1136 ctx.id AS ctxid, ctx.path AS ctxpath,
1137 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
3b8a284c 1138 FROM {course_categories} cc
1139 JOIN {context} ctx
1140 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
1141 WHERE cc.parent=?
40fb8aa6 1142 $sort";
3b8a284c 1143 $params = array($parent);
1144
02ebf404 1145 } else {
40fb8aa6 1146 $sql = "SELECT cc.*,
45ea1afb 1147 ctx.id AS ctxid, ctx.path AS ctxpath,
1148 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
3b8a284c 1149 FROM {course_categories} cc
1150 JOIN {context} ctx
1151 ON cc.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT."
1152 JOIN {course_categories} ccp
1153 ON (cc.path LIKE ".$DB->sql_concat('ccp.path',"'%'").")
1154 WHERE ccp.id=?
40fb8aa6 1155 $sort";
3b8a284c 1156 $params = array($parent);
02ebf404 1157 }
40fb8aa6 1158 $categories = array();
1159
3b8a284c 1160 if( $rs = $DB->get_recordset_sql($sql, $params) ){
1161 foreach($rs as $cat) {
40fb8aa6 1162 $cat = make_context_subobj($cat);
8ed5dd63 1163 if ($cat->visible || has_capability('moodle/category:viewhiddencategories',$cat->context)) {
40fb8aa6 1164 $categories[$cat->id] = $cat;
02ebf404 1165 }
1166 }
3b8a284c 1167 $rs->close();
02ebf404 1168 }
1169 return $categories;
1170}
1171
1172
2327b9df 1173/**
1174 * Returns an array of category ids of all the subcategories for a given
1175 * category.
1176 * @param $catid - The id of the category whose subcategories we want to find.
1177 * @return array of category ids.
1178 */
1179function get_all_subcategories($catid) {
3b8a284c 1180 global $DB;
2327b9df 1181
1182 $subcats = array();
1183
3b8a284c 1184 if ($categories = $DB->get_records('course_categories', array('parent'=>$catid))) {
2327b9df 1185 foreach ($categories as $cat) {
1186 array_push($subcats, $cat->id);
1187 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
1188 }
1189 }
1190 return $subcats;
1191}
1192
18a97fd8 1193/**
0cbe8111 1194 * Return specified category, default if given does not exist
1195 * @param int $catid course category id
1196 * @return object caregory
1197 */
1198function get_course_category($catid=0) {
1199 global $DB;
1200
1201 $category = false;
1202
1203 if (!empty($catid)) {
1204 $category = $DB->get_record('course_categories', array('id'=>$catid));
1205 }
8f0cd6ef 1206
0cbe8111 1207 if (!$category) {
1208 // the first category is considered default for now
1209 if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
1210 $category = reset($category);
1211
1212 } else {
1213 $cat = new object();
1214 $cat->name = get_string('miscellaneous');
1215 $cat->depth = 1;
1216 $cat->sortorder = MAX_COURSES_IN_CATEGORY;
1217 $cat->timemodified = time();
1218 if (!$catid = $DB->insert_record('course_categories', $cat)) {
1219 print_error('cannotsetupcategory', 'error');
1220 }
1221 // make sure category context exists
1222 get_context_instance(CONTEXT_COURSECAT, $catid);
1223 mark_context_dirty('/'.SYSCONTEXTID);
7a9d505b 1224 fix_course_sortorder(); // Required to build course_categories.depth and .path.
0cbe8111 1225 $category = $DB->get_record('course_categories', array('id'=>$catid));
f41ef63e 1226 }
0cbe8111 1227 }
ba87a4da 1228
0cbe8111 1229 return $category;
1230}
1231
1232/**
1233 * Fixes course category and course sortorder, also verifies category and course parents and paths.
a1b892cc 1234 * (circular references are not fixed)
0cbe8111 1235 */
1236function fix_course_sortorder() {
1237 global $DB, $SITE;
1238
1239 //WARNING: this is PHP5 only code!
1240
1241 if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
1242 //move all categories that are not sorted yet to the end
1243 $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
1244 }
1245
1246 $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
1247 $topcats = array();
1248 $brokencats = array();
1249 foreach ($allcats as $cat) {
1250 $sortorder = (int)$cat->sortorder;
1251 if (!$cat->parent) {
1252 while(isset($topcats[$sortorder])) {
1253 $sortorder++;
1254 }
1255 $topcats[$sortorder] = $cat;
1256 continue;
1257 }
1258 if (!isset($allcats[$cat->parent])) {
1259 $brokencats[] = $cat;
1260 continue;
c5d13b68 1261 }
0cbe8111 1262 if (!isset($allcats[$cat->parent]->children)) {
1263 $allcats[$cat->parent]->children = array();
c5d13b68 1264 }
0cbe8111 1265 while(isset($allcats[$cat->parent]->children[$sortorder])) {
1266 $sortorder++;
1267 }
1268 $allcats[$cat->parent]->children[$sortorder] = $cat;
f41ef63e 1269 }
0cbe8111 1270 unset($allcats);
39f65595 1271
0cbe8111 1272 // add broken cats to category tree
1273 if ($brokencats) {
1274 $defaultcat = reset($topcats);
1275 foreach ($brokencats as $cat) {
1276 $topcats[] = $cat;
a1b892cc 1277 }
ba87a4da 1278 }
1279
0cbe8111 1280 // now walk recursively the tree and fix any problems found
1281 $sortorder = 0;
1282 $fixcontexts = array();
1283 _fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts);
1284
1285 // detect if there are "multiple" frontpage courses and fix them if needed
1286 $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
1287 if (count($frontcourses) > 1) {
1288 if (isset($frontcourses[SITEID])) {
1289 $frontcourse = $frontcourses[SITEID];
1290 unset($frontcourses[SITEID]);
1291 } else {
1292 $frontcourse = array_shift($frontcourses);
1293 }
1294 $defaultcat = reset($topcats);
1295 foreach ($frontcourses as $course) {
1296 $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
1297 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1298 $fixcontexts[$context->id] = $context;
1299 }
1300 unset($frontcourses);
1301 } else {
1302 $frontcourse = reset($frontcourses);
814748c9 1303 }
1304
0cbe8111 1305 // now fix the paths and depths in context table if needed
1306 if ($fixcontexts) {
1307 rebuild_contexts($fixcontexts);
39f65595 1308 }
5930cded 1309
0cbe8111 1310 // release memory
1311 unset($topcats);
1312 unset($brokencats);
1313 unset($fixcontexts);
1314
1315 // fix frontpage course sortorder
1316 if ($frontcourse->sortorder != 1) {
1317 $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
39f65595 1318 }
1319
0cbe8111 1320 // now fix the course counts in category records if needed
1321 $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
1322 FROM {course_categories} cc
1323 LEFT JOIN {course} c ON c.category = cc.id
1324 GROUP BY cc.id, cc.coursecount
1325 HAVING cc.coursecount <> COUNT(c.id)";
ba87a4da 1326
0cbe8111 1327 if ($updatecounts = $DB->get_records_sql($sql)) {
1328 foreach ($updatecounts as $cat) {
1329 $cat->coursecount = $cat->newcount;
1330 unset($cat->newcount);
1331 $DB->update_record_raw('course_categories', $cat, true);
a1b892cc 1332 }
02ebf404 1333 }
8f0cd6ef 1334
0cbe8111 1335 // now make sure that sortorders in course table are withing the category sortorder ranges
8ed5dd63 1336 $sql = "SELECT DISTINCT cc.id, cc.sortorder
0cbe8111 1337 FROM {course_categories} cc
1338 JOIN {course} c ON c.category = cc.id
1339 WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
1340
1341 if ($fixcategories = $DB->get_records_sql($sql)) {
1342 //fix the course sortorder ranges
1343 foreach ($fixcategories as $cat) {
1344 $sql = "UPDATE {course}
78a0635c 1345 SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
0cbe8111 1346 WHERE category = ?";
1347 $DB->execute($sql, array($cat->sortorder, $cat->id));
1348 }
814748c9 1349 }
0cbe8111 1350 unset($fixcategories);
1351
1352 // categories having courses with sortorder duplicates or having gaps in sortorder
1353 $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
1354 FROM {course} c1
1355 JOIN {course} c2 ON c1.sortorder = c2.sortorder
1356 JOIN {course_categories} cc ON (c1.category = cc.id)
1357 WHERE c1.id <> c2.id";
1358 $fixcategories = $DB->get_records_sql($sql);
1359
1360 $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
1361 FROM {course_categories} cc
1362 JOIN {course} c ON c.category = cc.id
1363 GROUP BY cc.id, cc.sortorder, cc.coursecount
1364 HAVING (MAX(c.sortorder) <> cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <> cc.sortorder + 1)";
1365 $gapcategories = $DB->get_records_sql($sql);
1366
1367 foreach ($gapcategories as $cat) {
1368 if (isset($fixcategories[$cat->id])) {
1369 // duplicates detected already
1370
1371 } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
1372 // easy - new course inserted with sortorder 0, the rest is ok
1373 $sql = "UPDATE {course}
1374 SET sortorder = sortorder + 1
1375 WHERE category = ?";
1376 $DB->execute($sql, array($cat->id));
758b9a4d 1377
0cbe8111 1378 } else {
1379 // it needs full resorting
1380 $fixcategories[$cat->id] = $cat;
6bc502cc 1381 }
1382 }
0cbe8111 1383 unset($gapcategories);
8f0cd6ef 1384
0cbe8111 1385 // fix course sortorders in problematic categories only
1386 foreach ($fixcategories as $cat) {
1387 $i = 1;
1388 $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1389 foreach ($courses as $course) {
1390 if ($course->sortorder != $cat->sortorder + $i) {
1391 $course->sortorder = $cat->sortorder + $i;
a1b892cc 1392 $DB->update_record_raw('course', $course, true);
0cbe8111 1393 }
1394 $i++;
1395 }
1396 }
02ebf404 1397}
1398
d8634192 1399/**
0cbe8111 1400 * Internal recursive category verification function, do not use directly!
1401 */
1402function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
c3df0901 1403 global $DB;
d8634192 1404
0cbe8111 1405 $depth++;
c3df0901 1406
0cbe8111 1407 foreach ($children as $cat) {
1408 $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1409 $update = false;
1410 if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1411 $cat->parent = $parent;
1412 $cat->depth = $depth;
1413 $cat->path = $path.'/'.$cat->id;
1414 $update = true;
c3df0901 1415
0cbe8111 1416 // make sure context caches are rebuild and dirty contexts marked
1417 $context = get_context_instance(CONTEXT_COURSECAT, $cat->id);
1418 $fixcontexts[$context->id] = $context;
1419 }
1420 if ($cat->sortorder != $sortorder) {
1421 $cat->sortorder = $sortorder;
1422 $update = true;
1423 }
1424 if ($update) {
1425 $DB->update_record('course_categories', $cat, true);
1426 }
1427 if (isset($cat->children)) {
1428 _fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts);
d8634192 1429 }
1430 }
1431}
1432
db4b12eb 1433/**
1434 * List of remote courses that a user has access to via MNET.
1435 * Works only on the IDP
1436 *
1437 * @uses $CFG, $USER
1438 * @return array {@link $COURSE} of course objects
1439 */
1440function get_my_remotecourses($userid=0) {
c3df0901 1441 global $DB, $USER;
db4b12eb 1442
1443 if (empty($userid)) {
1444 $userid = $USER->id;
1445 }
1446
f76a259e 1447 $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
86dd62a7 1448 c.hostid, c.summary, c.cat_name,
1449 h.name AS hostname
c3df0901 1450 FROM {mnet_enrol_course} c
1451 JOIN {mnet_enrol_assignments} a ON c.id=a.courseid
1452 JOIN {mnet_host} h ON c.hostid=h.id
1453 WHERE a.userid=?";
db4b12eb 1454
c3df0901 1455 return $DB->get_records_sql($sql, array($userid));
db4b12eb 1456}
1457
1458/**
1459 * List of remote hosts that a user has access to via MNET.
1460 * Works on the SP
1461 *
1462 * @uses $CFG, $USER
1463 * @return array of host objects
1464 */
1465function get_my_remotehosts() {
1466 global $CFG, $USER;
1467
1468 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1469 return false; // Return nothing on the IDP
1470 }
1471 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1472 return $USER->mnet_foreign_host_array;
1473 }
1474 return false;
1475}
fbc21ae8 1476
18a97fd8 1477/**
fbc21ae8 1478 * This function creates a default separated/connected scale
1479 *
1480 * This function creates a default separated/connected scale
1481 * so there's something in the database. The locations of
1482 * strings and files is a bit odd, but this is because we
1483 * need to maintain backward compatibility with many different
1484 * existing language translations and older sites.
fbc21ae8 1485 */
02ebf404 1486function make_default_scale() {
c3df0901 1487 global $CFG, $DB;
02ebf404 1488
1489 $defaultscale = NULL;
1490 $defaultscale->courseid = 0;
1491 $defaultscale->userid = 0;
d4419d55 1492 $defaultscale->name = get_string('separateandconnected');
1493 $defaultscale->scale = get_string('postrating1', 'forum').','.
1494 get_string('postrating2', 'forum').','.
1495 get_string('postrating3', 'forum');
02ebf404 1496 $defaultscale->timemodified = time();
1497
8f0cd6ef 1498 /// Read in the big description from the file. Note this is not
02ebf404 1499 /// HTML (despite the file extension) but Moodle format text.
f191a887 1500 $parentlang = get_string('parentlanguage');
1501 if ($parentlang[0] == '[') {
1502 $parentlang = '';
1503 }
ee6e91d4 1504 if (is_readable($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1505 $file = file($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1506 } else if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
d4419d55 1507 $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
ee6e91d4 1508 } else if ($parentlang and is_readable($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1509 $file = file($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
d4419d55 1510 } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1511 $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
ee6e91d4 1512 } else if (is_readable($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html')) {
1513 $file = file($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html');
02ebf404 1514 } else {
d4419d55 1515 $file = '';
02ebf404 1516 }
1517
c3df0901 1518 $defaultscale->description = implode('', $file);
02ebf404 1519
c3df0901 1520 if ($defaultscale->id = $DB->insert_record('scale', $defaultscale)) {
1521 $DB->execute("UPDATE {forum} SET scale = ?", array($defaultscale->id));
02ebf404 1522 }
1523}
1524
fbc21ae8 1525
18a97fd8 1526/**
fbc21ae8 1527 * Returns a menu of all available scales from the site as well as the given course
1528 *
1529 * @uses $CFG
1530 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 1531 * @return object
fbc21ae8 1532 */
02ebf404 1533function get_scales_menu($courseid=0) {
c3df0901 1534 global $DB;
02ebf404 1535
c3df0901 1536 $sql = "SELECT id, name
1537 FROM {scale}
1538 WHERE courseid = 0 or courseid = ?
02ebf404 1539 ORDER BY courseid ASC, name ASC";
c3df0901 1540 $params = array($courseid);
02ebf404 1541
c3df0901 1542 if ($scales = $DB->get_records_sql_menu($sql, $params)) {
02ebf404 1543 return $scales;
1544 }
1545
1546 make_default_scale();
1547
c3df0901 1548 return $DB->get_records_sql_menu($sql, $params);
02ebf404 1549}
1550
5baa0ad6 1551
1552
1553/**
1554 * Given a set of timezone records, put them in the database, replacing what is there
1555 *
1556 * @uses $CFG
1557 * @param array $timezones An array of timezone records
1558 */
1559function update_timezone_records($timezones) {
c3df0901 1560 global $DB;
5baa0ad6 1561
1562/// Clear out all the old stuff
b820eb8c 1563 $DB->delete_records('timezone');
5baa0ad6 1564
1565/// Insert all the new stuff
1566 foreach ($timezones as $timezone) {
a599aeeb 1567 if (is_array($timezone)) {
1568 $timezone = (object)$timezone;
1569 }
c3df0901 1570 $DB->insert_record('timezone', $timezone);
5baa0ad6 1571 }
1572}
1573
1574
df28d6c5 1575/// MODULE FUNCTIONS /////////////////////////////////////////////////
1576
18a97fd8 1577/**
fbc21ae8 1578 * Just gets a raw list of all modules in a course
1579 *
fbc21ae8 1580 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 1581 * @return object
fbc21ae8 1582 */
9fa49e22 1583function get_course_mods($courseid) {
c3df0901 1584 global $DB;
9fa49e22 1585
3a11c548 1586 if (empty($courseid)) {
1587 return false; // avoid warnings
1588 }
1589
c3df0901 1590 return $DB->get_records_sql("SELECT cm.*, m.name as modname
1591 FROM {modules} m, {course_modules} cm
1592 WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1593 array($courseid)); // no disabled mods
9fa49e22 1594}
1595
fbc21ae8 1596
18a97fd8 1597/**
f9d5371b 1598 * Given an id of a course module, finds the coursemodule description
fbc21ae8 1599 *
a1b892cc 1600 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
f9d5371b 1601 * @param int $cmid course module id (id in course_modules table)
1602 * @param int $courseid optional course id for extra validation
a1b892cc 1603 * @param bool $sectionnum include relative section number (0,1,2 ...)
f9d5371b 1604 * @return object course module instance with instance and module name
1605 */
a1b892cc 1606function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false) {
c3df0901 1607 global $DB;
f9d5371b 1608
a1b892cc 1609 $params = array('cmid'=>$cmid);
1610
1611 if (!$modulename) {
1612 if (!$modulename = $DB->get_field_sql("SELECT md.name
1613 FROM {modules} md
1614 JOIN {course_modules} cm ON cm.module = md.id
1615 WHERE cm.id = :cmid", $params)) {
1616 return false;
1617 }
1618 }
1619
1620 $params['modulename'] = $modulename;
1621
d251907c 1622 $courseselect = "";
a1b892cc 1623 $sectionfield = "";
1624 $sectionjoin = "";
f9d5371b 1625
c3df0901 1626 if ($courseid) {
a1b892cc 1627 $courseselect = "AND cm.course = :courseid";
c3df0901 1628 $params['courseid'] = $courseid;
d251907c 1629 }
c3df0901 1630
a1b892cc 1631 if ($sectionnum) {
1632 $sectionfield = ", cw.section AS sectionnum";
1633 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1634 }
1635
1636 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1637 FROM {course_modules} cm
1638 JOIN {modules} md ON md.id = cm.module
1639 JOIN {".$modulename."} m ON m.id = cm.instance
1640 $sectionjoin
1641 WHERE cm.id = :cmid AND md.name = :modulename
1642 $courseselect";
1643
1644 return $DB->get_record_sql($sql, $params);
f9d5371b 1645}
1646
1647/**
1648 * Given an instance number of a module, finds the coursemodule description
1649 *
1650 * @param string $modulename name of module type, eg. resource, assignment,...
1651 * @param int $instance module instance number (id in resource, assignment etc. table)
1652 * @param int $courseid optional course id for extra validation
a1b892cc 1653 * @param bool $sectionnum include relative section number (0,1,2 ...)
f9d5371b 1654 * @return object course module instance with instance and module name
fbc21ae8 1655 */
a1b892cc 1656function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false) {
c3df0901 1657 global $DB;
df28d6c5 1658
a1b892cc 1659 $params = array('instance'=>$instance, 'modulename'=>$modulename);
1660
d251907c 1661 $courseselect = "";
a1b892cc 1662 $sectionfield = "";
1663 $sectionjoin = "";
df28d6c5 1664
c3df0901 1665 if ($courseid) {
a1b892cc 1666 $courseselect = "AND cm.course = :courseid";
c3df0901 1667 $params['courseid'] = $courseid;
d251907c 1668 }
c3df0901 1669
a1b892cc 1670 if ($sectionnum) {
1671 $sectionfield = ", cw.section AS sectionnum";
1672 $sectionjoin = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1673 }
1674
1675 $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1676 FROM {course_modules} cm
1677 JOIN {modules} md ON md.id = cm.module
1678 JOIN {".$modulename."} m ON m.id = cm.instance
1679 $sectionjoin
1680 WHERE m.id = :instance AND md.name = :modulename
1681 $courseselect";
df28d6c5 1682
a1b892cc 1683 return $DB->get_record_sql($sql, $params);
df28d6c5 1684}
1685
dd97c328 1686/**
1687 * Returns all course modules of given activity in course
1688 * @param string $modulename (forum, quiz, etc.)
1689 * @param int $courseid
1690 * @param string $extrafields extra fields starting with m.
1691 * @return array of cm objects, false if not found or error
1692 */
1693function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
c3df0901 1694 global $DB;
dd97c328 1695
1696 if (!empty($extrafields)) {
1697 $extrafields = ", $extrafields";
1698 }
c3df0901 1699 $params = array();
1700 $params['courseid'] = $courseid;
1701 $params['modulename'] = $modulename;
1702
1703
1704 return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1705 FROM {course_modules} cm, {modules} md, {".$modulename."} m
1706 WHERE cm.course = :courseid AND
1707 cm.instance = m.id AND
1708 md.name = :modulename AND
e0985504 1709 md.id = cm.module", $params);
dd97c328 1710}
ac0b1a19 1711
185cfb09 1712/**
1713 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1714 *
1715 * Returns an array of all the active instances of a particular
1716 * module in given courses, sorted in the order they are defined
ac0b1a19 1717 * in the course. Returns an empty array on any errors.
185cfb09 1718 *
ac0b1a19 1719 * The returned objects includle the columns cw.section, cm.visible,
1720 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
1721 *
1722 * @param string $modulename The name of the module to get instances for
1723 * @param array $courses an array of course objects.
1724 * @return array of module instance objects, including some extra fields from the course_modules
1725 * and course_sections tables, or an empty array if an error occurred.
185cfb09 1726 */
00e12c73 1727function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
c3df0901 1728 global $CFG, $DB;
ac0b1a19 1729
1730 $outputarray = array();
1731
185cfb09 1732 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
ac0b1a19 1733 return $outputarray;
185cfb09 1734 }
ac0b1a19 1735
c3df0901 1736 list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1737 $params['modulename'] = $modulename;
1738
1739 if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1740 cm.groupmode, cm.groupingid, cm.groupmembersonly
1741 FROM {course_modules} cm, {course_sections} cw, {modules} md,
1742 {".$modulename."} m
1743 WHERE cm.course $coursessql AND
1744 cm.instance = m.id AND
1745 cm.section = cw.id AND
1746 md.name = :modulename AND
1747 md.id = cm.module", $params)) {
ac0b1a19 1748 return $outputarray;
185cfb09 1749 }
1750
185cfb09 1751 foreach ($courses as $course) {
ac0b1a19 1752 $modinfo = get_fast_modinfo($course, $userid);
fea43a7f 1753
ac0b1a19 1754 if (empty($modinfo->instances[$modulename])) {
185cfb09 1755 continue;
1756 }
ac0b1a19 1757
1758 foreach ($modinfo->instances[$modulename] as $cm) {
1759 if (!$includeinvisible and !$cm->uservisible) {
1760 continue;
1761 }
1762 if (!isset($rawmods[$cm->id])) {
1763 continue;
185cfb09 1764 }
ac0b1a19 1765 $instance = $rawmods[$cm->id];
1766 if (!empty($cm->extra)) {
1767 $instance->extra = urlencode($cm->extra); // bc compatibility
1768 }
1769 $outputarray[] = $instance;
185cfb09 1770 }
1771 }
1772
1773 return $outputarray;
185cfb09 1774}
fbc21ae8 1775
18a97fd8 1776/**
3d96cba7 1777 * Returns an array of all the active instances of a particular module in a given course,
1778 * sorted in the order they are defined.
fbc21ae8 1779 *
1780 * Returns an array of all the active instances of a particular
1781 * module in a given course, sorted in the order they are defined
3d96cba7 1782 * in the course. Returns an empty array on any errors.
1783 *
1784 * The returned objects includle the columns cw.section, cm.visible,
ac0b1a19 1785 * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id.
fbc21ae8 1786 *
3d96cba7 1787 * @param string $modulename The name of the module to get instances for
ac0b1a19 1788 * @param object $course The course obect.
3d96cba7 1789 * @return array of module instance objects, including some extra fields from the course_modules
1790 * and course_sections tables, or an empty array if an error occurred.
fbc21ae8 1791 */
00e12c73 1792function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
ac0b1a19 1793 return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
df28d6c5 1794}
1795
9fa49e22 1796
18a97fd8 1797/**
fbc21ae8 1798 * Determine whether a module instance is visible within a course
1799 *
1800 * Given a valid module object with info about the id and course,
1801 * and the module's type (eg "forum") returns whether the object
dd97c328 1802 * is visible or not, groupmembersonly visibility not tested
fbc21ae8 1803 *
613bbd7c 1804 * @param $moduletype Name of the module eg 'forum'
1805 * @param $module Object which is the instance of the module
7290c7fa 1806 * @return bool
fbc21ae8 1807 */
580f2fbc 1808function instance_is_visible($moduletype, $module) {
c3df0901 1809 global $DB;
580f2fbc 1810
2b49ae96 1811 if (!empty($module->id)) {
d251907c 1812 $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
c3df0901 1813 if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
1814 FROM {course_modules} cm, {modules} m
1815 WHERE cm.course = :courseid AND
1816 cm.module = m.id AND
1817 m.name = :moduletype AND
f93ea222 1818 cm.instance = :moduleid", $params)) {
5930cded 1819
2b49ae96 1820 foreach ($records as $record) { // there should only be one - use the first one
dd97c328 1821 return $record->visible;
2b49ae96 1822 }
580f2fbc 1823 }
1824 }
580f2fbc 1825 return true; // visible by default!
1826}
1827
dd97c328 1828/**
1829 * Determine whether a course module is visible within a course,
1830 * this is different from instance_is_visible() - faster and visibility for user
1831 *
1832 * @param object $cm object
1833 * @param int $userid empty means current user
1834 * @return bool
1835 */
1836function coursemodule_visible_for_user($cm, $userid=0) {
82bd6a5e 1837 global $USER,$CFG;
dd97c328 1838
1839 if (empty($cm->id)) {
1840 debugging("Incorrect course module parameter!", DEBUG_DEVELOPER);
1841 return false;
1842 }
1843 if (empty($userid)) {
1844 $userid = $USER->id;
1845 }
1846 if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1847 return false;
1848 }
82bd6a5e 1849 if ($CFG->enableavailability) {
1850 require_once($CFG->libdir.'/conditionlib.php');
1851 $ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE);
1852 if(!$ci->is_available($cm->availableinfo,false,$userid) and
1853 !has_capability('moodle/course:viewhiddenactivities',
1854 get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
1855 return false;
1856 }
1857 }
dd97c328 1858 return groups_course_module_visible($cm, $userid);
1859}
1860
a3fb1c45 1861
1862
1863
9fa49e22 1864/// LOG FUNCTIONS /////////////////////////////////////////////////////
1865
1866
18a97fd8 1867/**
fbc21ae8 1868 * Add an entry to the log table.
1869 *
1870 * Add an entry to the log table. These are "action" focussed rather
1871 * than web server hits, and provide a way to easily reconstruct what
1872 * any particular student has been doing.
1873 *
1874 * @uses $CFG
1875 * @uses $USER
fbc21ae8 1876 * @uses $REMOTE_ADDR
1877 * @uses SITEID
89dcb99d 1878 * @param int $courseid The course id
fbc21ae8 1879 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
f7664880 1880 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
fbc21ae8 1881 * @param string $url The file and parameters used to see the results of the action
1882 * @param string $info Additional description information
1883 * @param string $cm The course_module->id if there is one
1884 * @param string $user If log regards $user other than $USER
1885 */
d4419d55 1886function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
e8395a09 1887 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1888 // This is for a good reason: it is the most frequently used DB update function,
1889 // so it has been optimised for speed.
f33e1ed4 1890 global $DB, $CFG, $USER;
9fa49e22 1891
7a5b1fc5 1892 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
f78b3c34 1893 $cm = 0;
1894 }
1895
3d94772d 1896 if ($user) {
1897 $userid = $user;
1898 } else {
b7b64ff2 1899 if (session_is_loggedinas()) { // Don't log
3d94772d 1900 return;
1901 }
d4419d55 1902 $userid = empty($USER->id) ? '0' : $USER->id;
9fa49e22 1903 }
1904
fcaff7ff 1905 $REMOTE_ADDR = getremoteaddr();
94b85686 1906 if (empty($REMOTE_ADDR)) {
1907 $REMOTE_ADDR = '0.0.0.0';
1908 }
fcaff7ff 1909
9fa49e22 1910 $timenow = time();
ac1ba33e 1911 $info = $info;
10a760b9 1912 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1913 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
1914 }
853df85e 1915
6c5a2108 1916 // Restrict length of log lines to the space actually available in the
1917 // database so that it doesn't cause a DB error. Log a warning so that
1918 // developers can avoid doing things which are likely to cause this on a
1919 // routine basis.
ac1ba33e 1920 $tl = textlib_get_instance();
6c5a2108 1921 if(!empty($info) && $tl->strlen($info)>255) {
ac1ba33e 1922 $info = $tl->substr($info,0,252).'...';
6c5a2108 1923 debugging('Warning: logged very long info',DEBUG_DEVELOPER);
1924 }
ac1ba33e 1925
6c5a2108 1926 // If the 100 field size is changed, also need to alter print_log in course/lib.php
1927 if(!empty($url) && $tl->strlen($url)>100) {
1928 $url=$tl->substr($url,0,97).'...';
1929 debugging('Warning: logged very long URL',DEBUG_DEVELOPER);
1930 }
8a445484 1931
f33e1ed4 1932 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->logwrites++;};
853df85e 1933
8b497bbc 1934 if ($CFG->type = 'oci8po') {
f33e1ed4 1935 if ($info == '') {
8b497bbc 1936 $info = ' ';
1937 }
1938 }
f33e1ed4 1939 $log = array('time'=>$timenow, 'userid'=>$userid, 'course'=>$courseid, 'ip'=>$REMOTE_ADDR, 'module'=>$module,
1940 'cmid'=>$cm, 'action'=>$action, 'url'=>$url, 'info'=>$info);
1941 $result = $DB->insert_record_raw('log', $log, false);
ebc3bd2b 1942
9f064546 1943 // MDL-11893, alert $CFG->supportemail if insert into log failed
f33e1ed4 1944 if (!$result and $CFG->supportemail and empty($CFG->noemailever)) {
1945 // email_to_user is not usable because email_to_user tries to write to the logs table,
1946 // and this will get caught in an infinite loop, if disk is full
9f064546 1947 $site = get_site();
1948 $subject = 'Insert into log failed at your moodle site '.$site->fullname;
0fdf06cd 1949 $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";
f33e1ed4 1950 $message .= "The failed query parameters are:\n\n" . var_export($log, true);
0fdf06cd 1951
f33e1ed4 1952 $lasttime = get_config('admin', 'lastloginserterrormail');
1953 if(empty($lasttime) || time() - $lasttime > 60*60*24) { // limit to 1 email per day
1954 mail($CFG->supportemail, $subject, $message);
1955 set_config('lastloginserterrormail', time(), 'admin');
58538527 1956 }
9f064546 1957 }
1958
252720c4 1959 if (!$result) {
1960 debugging('Error: Could not insert a new entry to the Moodle log', DEBUG_ALL);
8f0cd6ef 1961 }
cb80265b 1962
341b5ed2 1963}
1964
1965/**
1966 * Store user last access times - called when use enters a course or site
1967 *
341b5ed2 1968 * @param int $courseid, empty means site
1969 * @return void
1970 */
1971function user_accesstime_log($courseid=0) {
f33e1ed4 1972 global $USER, $CFG, $DB;
341b5ed2 1973
b7b64ff2 1974 if (!isloggedin() or session_is_loggedinas()) {
341b5ed2 1975 // no access tracking
1976 return;
1977 }
1978
1979 if (empty($courseid)) {
1980 $courseid = SITEID;
1981 }
1982
1983 $timenow = time();
1984
1985/// Store site lastaccess time for the current user
1986 if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1987 /// Update $USER->lastaccess for next checks
1988 $USER->lastaccess = $timenow;
341b5ed2 1989
f33e1ed4 1990 $last = new object();
1991 $last->id = $USER->id;
1992 $last->lastip = getremoteaddr();
1993 $last->lastaccess = $timenow;
1994
68fbad44 1995 $DB->update_record_raw('user', $last);
341b5ed2 1996 }
1997
1998 if ($courseid == SITEID) {
1999 /// no user_lastaccess for frontpage
2000 return;
2001 }
cb8aaedf 2002
341b5ed2 2003/// Store course lastaccess times for the current user
2004 if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
341b5ed2 2005
f33e1ed4 2006 $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
341b5ed2 2007
f33e1ed4 2008 if ($lastaccess === false) {
2009 // Update course lastaccess for next checks
2010 $USER->currentcourseaccess[$courseid] = $timenow;
2011
2012 $last = new object();
2013 $last->userid = $USER->id;
2014 $last->courseid = $courseid;
2015 $last->timeaccess = $timenow;
68fbad44 2016 $DB->insert_record_raw('user_lastaccess', $last, false);
d251907c 2017
f33e1ed4 2018 } else if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) {
2019 // no need to update now, it was updated recently in concurrent login ;-)
341b5ed2 2020
f33e1ed4 2021 } else {
2022 // Update course lastaccess for next checks
2023 $USER->currentcourseaccess[$courseid] = $timenow;
2024
68fbad44 2025 $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
3d94772d 2026 }
8f0cd6ef 2027 }
9fa49e22 2028}
2029
18a97fd8 2030/**
fbc21ae8 2031 * Select all log records based on SQL criteria
2032 *
fbc21ae8 2033 * @param string $select SQL select criteria
c3df0901 2034 * @param array $params named sql type params
fbc21ae8 2035 * @param string $order SQL order by clause to sort the records returned
2036 * @param string $limitfrom ?
2037 * @param int $limitnum ?
2038 * @param int $totalcount Passed in by reference.
7290c7fa 2039 * @return object
fbc21ae8 2040 * @todo Finish documenting this function
2041 */
c3df0901 2042function get_logs($select, array $params=null, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
2043 global $DB;
9fa49e22 2044
519d369f 2045 if ($order) {
c3df0901 2046 $order = "ORDER BY $order";
2047 }
2048
2049 $selectsql = "";
2050 $countsql = "";
2051
2052 if ($select) {
2053 $select = "WHERE $select";
519d369f 2054 }
2055
c3df0901 2056 $sql = "SELECT COUNT(*)
2057 FROM {log} l
2058 $select";
2059
2060 $totalcount = $DB->count_records_sql($sql, $params);
a2ddd957 2061
c3df0901 2062 $sql = "SELECT l.*, u.firstname, u.lastname, u.picture
d251907c 2063 FROM {log} l
c3df0901 2064 LEFT JOIN {user} u ON l.userid = u.id
d251907c 2065 $select
c3df0901 2066 $order";
519d369f 2067
c3df0901 2068 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum) ;
9fa49e22 2069}
2070
519d369f 2071
18a97fd8 2072/**
fbc21ae8 2073 * Select all log records for a given course and user
2074 *
2075 * @uses $CFG
2f87145b 2076 * @uses DAYSECS
fbc21ae8 2077 * @param int $userid The id of the user as found in the 'user' table.
2078 * @param int $courseid The id of the course as found in the 'course' table.
2079 * @param string $coursestart ?
2080 * @todo Finish documenting this function
2081 */
9fa49e22 2082function get_logs_usercourse($userid, $courseid, $coursestart) {
c3df0901 2083 global $DB;
9fa49e22 2084
c3df0901 2085 $params = array();
2086
2087 $courseselect = '';
da0c90c3 2088 if ($courseid) {
c3df0901 2089 $courseselect = "AND course = :courseid";
d251907c 2090 $params['courseid'] = $courseid;
da0c90c3 2091 }
c3df0901 2092 $params['userid'] = $userid;
d251907c 2093 $params['coursestart'] = $coursestart;
da0c90c3 2094
c3df0901 2095 return $DB->get_records_sql("SELECT FLOOR((time - :coursestart)/". DAYSECS .") AS day, COUNT(*) AS num
2096 FROM {log}
2097 WHERE userid = :userid
2098 AND time > :coursestart $courseselect
2099 GROUP BY FLOOR((time - :coursestart)/". DAYSECS .")", $params);
9fa49e22 2100}
2101
18a97fd8 2102/**
fbc21ae8 2103 * Select all log records for a given course, user, and day
2104 *
2105 * @uses $CFG
2f87145b 2106 * @uses HOURSECS
fbc21ae8 2107 * @param int $userid The id of the user as found in the 'user' table.
2108 * @param int $courseid The id of the course as found in the 'course' table.
2109 * @param string $daystart ?
7290c7fa 2110 * @return object
fbc21ae8 2111 * @todo Finish documenting this function
2112 */
9fa49e22 2113function get_logs_userday($userid, $courseid, $daystart) {
c3df0901 2114 global $DB;
2115
2116 $params = array();
9fa49e22 2117
c3df0901 2118 $courseselect = '';
7e4a6488 2119 if ($courseid) {
c3df0901 2120 $courseselect = "AND course = :courseid";
d251907c 2121 $params['courseid'] = $courseid;
7e4a6488 2122 }
c3df0901 2123 $params['userid'] = $userid;
d251907c 2124 $params['daystart'] = $daystart;
7e4a6488 2125
c3df0901 2126 return $DB->get_records_sql("SELECT FLOOR((time - :daystart)/". HOURSECS .") AS hour, COUNT(*) AS num
2127 FROM {log}
2128 WHERE userid = :userid
2129 AND time > :daystart $courseselect
2130 GROUP BY FLOOR((time - :daystart)/". HOURSECS .") ");
9fa49e22 2131}
2132
b4bac9b6 2133/**
2134 * Returns an object with counts of failed login attempts
2135 *
8f0cd6ef 2136 * Returns information about failed login attempts. If the current user is
2137 * an admin, then two numbers are returned: the number of attempts and the
b4bac9b6 2138 * number of accounts. For non-admins, only the attempts on the given user
2139 * are shown.
2140 *
fbc21ae8 2141 * @param string $mode Either 'admin', 'teacher' or 'everybody'
2142 * @param string $username The username we are searching for
2143 * @param string $lastlogin The date from which we are searching
2144 * @return int
b4bac9b6 2145 */
b4bac9b6 2146function count_login_failures($mode, $username, $lastlogin) {
c3df0901 2147 global $DB;
b4bac9b6 2148
c3df0901 2149 $params = array('mode'=>$mode, 'username'=>$username, 'lastlogin'=>$lastlogin);
2150 $select = "module='login' AND action='error' AND time > :lastlogin";
2151
2152 $count = new object();
b4bac9b6 2153
12d06877 2154 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { // Return information about all accounts
c3df0901 2155 if ($count->attempts = $DB->count_records_select('log', $select, $params)) {
2156 $count->accounts = $DB->count_records_select('log', $select, $params, 'COUNT(DISTINCT info)');
b4bac9b6 2157 return $count;
2158 }
9407d456 2159 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
c3df0901 2160 if ($count->attempts = $DB->count_records_select('log', "$select AND info = :username", $params)) {
b4bac9b6 2161 return $count;
2162 }
2163 }
2164 return NULL;
2165}
2166
2167
a3fb1c45 2168/// GENERAL HELPFUL THINGS ///////////////////////////////////
2169
18a97fd8 2170/**
fbc21ae8 2171 * Dump a given object's information in a PRE block.
2172 *
2173 * Mostly just used for debugging.
2174 *
2175 * @param mixed $object The data to be printed
fbc21ae8 2176 */
a3fb1c45 2177function print_object($object) {
1aa7b31d 2178 echo '<pre class="notifytiny">' . htmlspecialchars(print_r($object,true)) . '</pre>';
a3fb1c45 2179}
2180
624a690b 2181/**
3511647c 2182 * Check whether a course is visible through its parents
bfbfdb53 2183 * path.
3511647c 2184 *
2185 * Notes:
2186 *
2187 * - All we need from the course is ->category. _However_
2188 * if the course object has a categorypath property,
2189 * we'll save a dbquery
2190 *
2191 * - If we return false, you'll still need to check if
8ed5dd63 2192 * the user can has the 'moodle/category:viewhiddencategories'
3511647c 2193 * capability...
2194 *
bfbfdb53 2195 * - Will generate 2 DB calls.
3511647c 2196 *
2197 * - It does have a small local cache, however...
2198 *
2199 * - Do NOT call this over many courses as it'll generate
2200 * DB traffic. Instead, see what get_my_courses() does.
2201 *
2202 * @param mixed $object A course object
2203 * @return bool
2204 */
0986271b 2205function course_parent_visible($course = null) {
c3df0901 2206 global $CFG, $DB;
3511647c 2207 //return true;
2208 static $mycache;
fa145ae1 2209
3511647c 2210 if (!is_object($course)) {
418b4e5a 2211 return true;
2212 }
2213 if (!empty($CFG->allowvisiblecoursesinhiddencategories)) {
2214 return true;
2215 }
0986271b 2216
3511647c 2217 if (!isset($mycache)) {
2218 $mycache = array();
2219 } else {
2220 // cast to force assoc array
bfbfdb53 2221 $k = (string)$course->category;
3511647c 2222 if (isset($mycache[$k])) {
2223 return $mycache[$k];
2224 }
0986271b 2225 }
5930cded 2226
3511647c 2227 if (isset($course->categorypath)) {
2228 $path = $course->categorypath;
2229 } else {
c3df0901 2230 $path = $DB->get_field('course_categories', 'path', array('id'=>$course->category));
824f1c40 2231 }
3511647c 2232 $catids = substr($path,1); // strip leading slash
2233 $catids = str_replace('/',',',$catids);
824f1c40 2234
3511647c 2235 $sql = "SELECT MIN(visible)
c3df0901 2236 FROM {course_categories}
2237 WHERE id IN ($catids)";
2238 $vis = $DB->get_field_sql($sql);
5930cded 2239
3511647c 2240 // cast to force assoc array
2241 $k = (string)$course->category;
2242 $mycache[$k] = $vis;
2243
2244 return $vis;
0986271b 2245}
2246
62d4e774 2247/**
5930cded 2248 * This function is the official hook inside XMLDB stuff to delegate its debug to one
62d4e774 2249 * external function.
2250 *
2251 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
2252 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
2253 *
2254 * @param $message string contains the error message
2255 * @param $object object XMLDB object that fired the debug
2256 */
2257function xmldb_debug($message, $object) {
2258
92b564f4 2259 debugging($message, DEBUG_DEVELOPER);
62d4e774 2260}
2261
49860445 2262/**
df73f8d4 2263 * @return boolean Whether the user can create courses in any category in the system.
49860445 2264 */
2265function user_can_create_courses() {
c3df0901 2266 global $DB;
df73f8d4 2267 $catsrs = $DB->get_recordset('course_categories');
4d55255b 2268 foreach ($catsrs as $cat) {
df73f8d4 2269 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) {
2270 $catsrs->close();
2271 return true;
49860445 2272 }
2273 }
df73f8d4 2274 $catsrs->close();
2275 return false;
49860445 2276}
2277
03517306 2278?>