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