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