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