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