accesslib: introducing make_context_subobj() - and refactor callers
[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();
5930cded 511 if (!($courses = get_records_sql("SELECT $fields
512 FROM {$CFG->prefix}course c
71dea306 513 $categoryselect
12490fc2 514 ORDER BY $sort"))) {
515 return $visiblecourses;
516 }
71dea306 517 $totalcount = 0;
5930cded 518
71dea306 519 if (!$limitnum) {
5930cded 520 $limitnum = count($courses);
71dea306 521 }
5930cded 522
285f94f5 523 if (!$limitfrom) {
5930cded 524 $limitfrom = 0;
71dea306 525 }
5930cded 526
71dea306 527 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
528 foreach ($courses as $course) {
529 if ($course->visible <= 0) {
530 // for hidden courses, require visibility check
531 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
532 $totalcount++;
533 if ($totalcount > $limitfrom && count($visiblecourses) < $limitnum) {
534 $visiblecourses [] = $course;
535 }
536 }
537 } else {
538 $totalcount++;
539 if ($totalcount > $limitfrom && count($visiblecourses) < $limitnum) {
540 $visiblecourses [] = $course;
541 }
5930cded 542 }
71dea306 543 }
5930cded 544
71dea306 545 return $visiblecourses;
546
547/**
8130b77b 548
6315b1c8 549 $categoryselect = "";
b565bbdf 550 if ($categoryid != "all" && is_numeric($categoryid)) {
6315b1c8 551 $categoryselect = "c.category = '$categoryid'";
8130b77b 552 }
553
6315b1c8 554 $teachertable = "";
555 $visiblecourses = "";
556 $sqland = "";
557 if (!empty($categoryselect)) {
558 $sqland = "AND ";
c7fe5c6f 559 }
2d2da684 560 if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
ae9e4c06 561 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
6315b1c8 562 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
563 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
564 }
8130b77b 565 } else {
6315b1c8 566 $visiblecourses = "$sqland c.visible > 0";
8130b77b 567 }
568
6315b1c8 569 if ($limitfrom !== "") {
29daf3a0 570 $limit = sql_paging_limit($limitfrom, $limitnum);
6315b1c8 571 } else {
572 $limit = "";
02ebf404 573 }
8ef9cb56 574
6315b1c8 575 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
8ef9cb56 576
6315b1c8 577 $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
8ef9cb56 578
2338ad32 579 return get_records_sql("SELECT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
71dea306 580 */
02ebf404 581}
582
583
18a97fd8 584/**
f8e1c7af 585 * List of courses that a user has access to view. Note that for admins,
586 * this usually includes every course on the system.
fbc21ae8 587 *
573674bf 588 * Notes (inherited from get_user_courses_bycap()):
e1d5e5c1 589 *
590 * - $fields is an array of fieldnames to ADD
591 * so name the fields you really need, which will
592 * be added and uniq'd
593 *
594 * - the course records have $c->context which is a fully
595 * valid context object. Saves you a query per course!
596 *
352f6f74 597 * @uses $CFG,$USER
7290c7fa 598 * @param int $userid The user of interest
33f85740 599 * @param string $sort the sortorder in the course table
e1d5e5c1 600 * @param array $fields - names of _additional_ fields to return (also accepts a string)
f8e1c7af 601 * @param bool $doanything True if using the doanything flag
602 * @param int $limit Maximum number of records to return, or 0 for unlimited
33f85740 603 * @return array {@link $COURSE} of course objects
fbc21ae8 604 */
e1d5e5c1 605function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
bdf3bbd1 606
352f6f74 607 global $CFG,$USER;
5930cded 608
4dbca99e 609 // Guest's do not have any courses
e1d5e5c1 610 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
61f774e8 611 if (has_capability('moodle/legacy:guest',$sitecontext,$userid,false)) {
4dbca99e 612 return(array());
613 }
601edb90 614
352f6f74 615 $basefields = array('id', 'category', 'sortorder',
616 'shortname', 'fullname', 'idnumber',
617 'teacher', 'teachers', 'student', 'students',
618 'guest', 'startdate', 'visible',
619 'newsitems', 'cost', 'enrol',
620 'groupmode', 'groupmodeforce');
621
e1d5e5c1 622 if (!is_null($fields) && is_string($fields)) {
623 if (empty($fields)) {
352f6f74 624 $fields = $basefields;
e1d5e5c1 625 } else {
626 // turn the fields from a string to an array that
573674bf 627 // get_user_courses_bycap() will like...
352f6f74 628 $fields = explode(',',$fields);
629 $fields = array_map('trim', $fields);
630 $fields = array_unique(array_merge($basefields, $fields));
631 }
632 } else {
633 $fields = $basefields;
634 }
635
636 //
637 // Logged-in user - Check cached courses
638 //
639 // NOTE! it's a _string_ because
640 // - it's all we'll ever use
641 // - it serialises much more compact than an array
642 // this a BIG concern here - cost of serialise
643 // and unserialise is HUGE if the session grows
644 //
645 // If the courses are too many - it won't be set
646 // for large numbers of courses, caching in the session
647 // has marginal benefits (costs too much, not
648 // worthwhile...) and we may hit SQL parser limits
649 // because we use IN()
650 //
ae1555ae 651 if ($userid === $USER->id) {
fe3141e0 652 if (isset($USER->loginascontext)
653 && $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
ae1555ae 654 // list _only_ this course
655 // anything else is asking for trouble...
656 $courseids = $USER->loginascontext->instanceid;
657 } elseif (isset($USER->mycourses)
658 && is_string($USER->mycourses)) {
659 if ($USER->mycourses === '') {
660 // empty str means: user has no courses
661 // ... so do the easy thing...
662 return array();
663 } else {
664 $courseids = $USER->mycourses;
665 }
666 }
667 if (isset($courseids)) {
352f6f74 668 // The data massaging here MUST be kept in sync with
669 // get_user_courses_bycap() so we return
670 // the same...
671 // (but here we don't need to check has_cap)
672 $coursefields = 'c.' .join(',c.', $fields);
673 $sql = "SELECT $coursefields,
674 ctx.id AS ctxid, ctx.path AS ctxpath, ctx.depth as ctxdepth
675 FROM {$CFG->prefix}course c
676 JOIN {$CFG->prefix}context ctx
677 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
ae1555ae 678 WHERE c.id IN ($courseids)
352f6f74 679 ORDER BY $sort";
680 $rs = get_recordset_sql($sql);
681 $courses = array();
682 $cc = 0; // keep count
683 if ($rs->RecordCount()) {
684 while ($c = rs_fetch_next_record($rs)) {
685 // build the context obj
c1b7a5e5 686 $c = make_context_subobj($c);
687
352f6f74 688 $courses[$c->id] = $c;
689 if ($limit > 0 && $cc++ > $limit) {
690 break;
691 }
692 }
693 }
694 rs_close($rs);
695 return $courses;
2f3499b7 696 }
697 }
152a9060 698
352f6f74 699 // Non-cached - get accessinfo
e1d5e5c1 700 if ($userid === $USER->id && isset($USER->access)) {
aeb3916b 701 $accessinfo = $USER->access;
bdf3bbd1 702 } else {
e1d5e5c1 703 $accessinfo = get_user_access_sitewide($userid);
aeb3916b 704 }
352f6f74 705
706
573674bf 707 $courses = get_user_courses_bycap($userid, 'moodle/course:view', $accessinfo,
708 $doanything, $sort, $fields,
709 $limit);
352f6f74 710
711 //
712 // Strangely, get_my_courses() is expected to return the
aeb3916b 713 // array keyed on id, which messes up the sorting
352f6f74 714 // So do that, and also cache the ids in the session if appropriate
715 //
aeb3916b 716 $kcourses = array();
717 $cc = count($courses);
352f6f74 718 $cacheids = NULL;
719 if ($userid === $USER->id && $cc < 500) {
720 $cacheids = array();
721 }
aeb3916b 722 for ($n=0; $n<$cc; $n++) {
723 $kcourses[$courses[$n]->id] = $courses[$n];
352f6f74 724 if (is_array($cacheids)) {
725 $cacheids[] = $courses[$n]->id;
726 }
727 }
728 if (is_array($cacheids)) {
729 // Only happens
730 // - for the logged in user
731 // - below the threshold (500)
732 // empty string is _valid_
733 $USER->mycourses = join(',',$cacheids);
734 } elseif ($userid === $USER->id && isset($USER->mycourses)) {
735 // cheap sanity check
736 unset($USER->mycourses);
aeb3916b 737 }
352f6f74 738
aeb3916b 739 return $kcourses;
02ebf404 740}
741
18a97fd8 742/**
7290c7fa 743 * A list of courses that match a search
fbc21ae8 744 *
745 * @uses $CFG
746 * @param array $searchterms ?
747 * @param string $sort ?
748 * @param int $page ?
749 * @param int $recordsperpage ?
750 * @param int $totalcount Passed in by reference. ?
7290c7fa 751 * @return object {@link $COURSE} records
fbc21ae8 752 */
d4419d55 753function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
02ebf404 754
755 global $CFG;
756
18a97fd8 757 //to allow case-insensitive search for postgesql
48505662 758 if ($CFG->dbfamily == 'postgres') {
d4419d55 759 $LIKE = 'ILIKE';
760 $NOTLIKE = 'NOT ILIKE'; // case-insensitive
761 $REGEXP = '~*';
762 $NOTREGEXP = '!~*';
02ebf404 763 } else {
d4419d55 764 $LIKE = 'LIKE';
765 $NOTLIKE = 'NOT LIKE';
766 $REGEXP = 'REGEXP';
767 $NOTREGEXP = 'NOT REGEXP';
02ebf404 768 }
769
d4419d55 770 $fullnamesearch = '';
771 $summarysearch = '';
02ebf404 772
02ebf404 773 foreach ($searchterms as $searchterm) {
6bb0f67f 774
775 /// Under Oracle and MSSQL, trim the + and - operators and perform
776 /// simpler LIKE search
48505662 777 if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
6bb0f67f 778 $searchterm = trim($searchterm, '+-');
779 }
780
02ebf404 781 if ($fullnamesearch) {
d4419d55 782 $fullnamesearch .= ' AND ';
02ebf404 783 }
02ebf404 784 if ($summarysearch) {
d4419d55 785 $summarysearch .= ' AND ';
02ebf404 786 }
a8b56716 787
d4419d55 788 if (substr($searchterm,0,1) == '+') {
a8b56716 789 $searchterm = substr($searchterm,1);
790 $summarysearch .= " summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
791 $fullnamesearch .= " fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
792 } else if (substr($searchterm,0,1) == "-") {
793 $searchterm = substr($searchterm,1);
794 $summarysearch .= " summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
795 $fullnamesearch .= " fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
796 } else {
5930cded 797 $summarysearch .= ' summary '. $LIKE .' \'%'. $searchterm .'%\' ';
798 $fullnamesearch .= ' fullname '. $LIKE .' \'%'. $searchterm .'%\' ';
a8b56716 799 }
800
02ebf404 801 }
802
d4419d55 803 $selectsql = $CFG->prefix .'course WHERE ('. $fullnamesearch .' OR '. $summarysearch .') AND category > \'0\'';
a8b56716 804
d4419d55 805 $totalcount = count_records_sql('SELECT COUNT(*) FROM '. $selectsql);
02ebf404 806
422770d8 807 $courses = get_records_sql('SELECT * FROM '. $selectsql .' ORDER BY '. $sort, $page, $recordsperpage);
02ebf404 808
809 if ($courses) { /// Remove unavailable courses from the list
810 foreach ($courses as $key => $course) {
152a9060 811 if (!$course->visible) {
1c45e42e 812 if (!has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
02ebf404 813 unset($courses[$key]);
a8b56716 814 $totalcount--;
02ebf404 815 }
816 }
817 }
818 }
819
820 return $courses;
821}
822
823
18a97fd8 824/**
fbc21ae8 825 * Returns a sorted list of categories
826 *
613bbd7c 827 * @param string $parent The parent category if any
828 * @param string $sort the sortorder
829 * @return array of categories
fbc21ae8 830 */
d4419d55 831function get_categories($parent='none', $sort='sortorder ASC') {
02ebf404 832
814748c9 833 if ($parent === 'none') {
d4419d55 834 $categories = get_records('course_categories', '', '', $sort);
02ebf404 835 } else {
d4419d55 836 $categories = get_records('course_categories', 'parent', $parent, $sort);
02ebf404 837 }
838 if ($categories) { /// Remove unavailable categories from the list
02ebf404 839 foreach ($categories as $key => $category) {
152a9060 840 if (!$category->visible) {
115a622d 841 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $category->id))) {
02ebf404 842 unset($categories[$key]);
843 }
844 }
845 }
846 }
847 return $categories;
848}
849
850
2327b9df 851/**
852 * Returns an array of category ids of all the subcategories for a given
853 * category.
854 * @param $catid - The id of the category whose subcategories we want to find.
855 * @return array of category ids.
856 */
857function get_all_subcategories($catid) {
858
859 $subcats = array();
860
861 if ($categories = get_records('course_categories', 'parent', $catid)) {
862 foreach ($categories as $cat) {
863 array_push($subcats, $cat->id);
864 $subcats = array_merge($subcats, get_all_subcategories($cat->id));
865 }
866 }
867 return $subcats;
868}
869
870
18a97fd8 871/**
ba87a4da 872* This recursive function makes sure that the courseorder is consecutive
873*
874* @param type description
875*
876* $n is the starting point, offered only for compatilibity -- will be ignored!
877* $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
878* safely from 1.4 to 1.5
879*/
f41ef63e 880function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
5930cded 881
ba87a4da 882 global $CFG;
8f0cd6ef 883
02ebf404 884 $count = 0;
5930cded 885
f41ef63e 886 $catgap = 1000; // "standard" category gap
887 $tolerance = 200; // how "close" categories can get
5930cded 888
f41ef63e 889 if ($categoryid > 0){
890 // update depth and path
891 $cat = get_record('course_categories', 'id', $categoryid);
892 if ($cat->parent == 0) {
893 $depth = 0;
894 $path = '';
895 } else if ($depth == 0 ) { // doesn't make sense; get from DB
896 // this is only called if the $depth parameter looks dodgy
897 $parent = get_record('course_categories', 'id', $cat->parent);
898 $path = $parent->path;
899 $depth = $parent->depth;
900 }
901 $path = $path . '/' . $categoryid;
902 $depth = $depth + 1;
ba87a4da 903
5930cded 904 set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
905 set_field('course_categories', 'depth', $depth, 'id', $categoryid);
f41ef63e 906 }
39f65595 907
908 // get some basic info about courses in the category
5930cded 909 $info = get_record_sql('SELECT MIN(sortorder) AS min,
ba87a4da 910 MAX(sortorder) AS max,
5930cded 911 COUNT(sortorder) AS count
912 FROM ' . $CFG->prefix . 'course
ba87a4da 913 WHERE category=' . $categoryid);
914 if (is_object($info)) { // no courses?
915 $max = $info->max;
916 $count = $info->count;
917 $min = $info->min;
918 unset($info);
919 }
920
814748c9 921 if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
922 $n = $min;
923 }
924
39f65595 925 // $hasgap flag indicates whether there's a gap in the sequence
5930cded 926 $hasgap = false;
39f65595 927 if ($max-$min+1 != $count) {
928 $hasgap = true;
929 }
5930cded 930
39f65595 931 // $mustshift indicates whether the sequence must be shifted to
932 // meet its range
933 $mustshift = false;
934 if ($min < $n+$tolerance || $min > $n+$tolerance+$catgap ) {
935 $mustshift = true;
936 }
937
ba87a4da 938 // actually sort only if there are courses,
939 // and we meet one ofthe triggers:
940 // - safe flag
941 // - they are not in a continuos block
942 // - they are too close to the 'bottom'
39f65595 943 if ($count && ( $safe || $hasgap || $mustshift ) ) {
944 // special, optimized case where all we need is to shift
945 if ( $mustshift && !$safe && !$hasgap) {
946 $shift = $n + $catgap - $min;
f8ea6077 947 if ($shift < $count) {
948 $shift = $count + $catgap;
949 }
39f65595 950 // UPDATE course SET sortorder=sortorder+$shift
5930cded 951 execute_sql("UPDATE {$CFG->prefix}course
952 SET sortorder=sortorder+$shift
39f65595 953 WHERE category=$categoryid", 0);
5930cded 954 $n = $n + $catgap + $count;
955
39f65595 956 } else { // do it slowly
5930cded 957 $n = $n + $catgap;
39f65595 958 // if the new sequence overlaps the current sequence, lack of transactions
959 // will stop us -- shift things aside for a moment...
48505662 960 if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbfamily==='mysql')) {
d6a49dab 961 $shift = $max + $n + 1000;
5930cded 962 execute_sql("UPDATE {$CFG->prefix}course
963 SET sortorder=sortorder+$shift
39f65595 964 WHERE category=$categoryid", 0);
ba87a4da 965 }
966
39f65595 967 $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
968 begin_sql();
f8ea6077 969 $tx = true; // transaction sanity
5930cded 970 foreach ($courses as $course) {
f8ea6077 971 if ($tx && $course->sortorder != $n ) { // save db traffic
972 $tx = $tx && set_field('course', 'sortorder', $n,
973 'id', $course->id);
ba87a4da 974 }
975 $n++;
976 }
f8ea6077 977 if ($tx) {
978 commit_sql();
979 } else {
980 rollback_sql();
981 if (!$safe) {
982 // if we failed when called with !safe, try
983 // to recover calling self with safe=true
984 return fix_course_sortorder($categoryid, $n, true, $depth, $path);
985 }
986 }
5930cded 987 }
02ebf404 988 }
d4419d55 989 set_field('course_categories', 'coursecount', $count, 'id', $categoryid);
8f0cd6ef 990
5930cded 991 // $n could need updating
814748c9 992 $max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid");
993 if ($max > $n) {
994 $n = $max;
995 }
758b9a4d 996
6bc502cc 997 if ($categories = get_categories($categoryid)) {
998 foreach ($categories as $category) {
f41ef63e 999 $n = fix_course_sortorder($category->id, $n, $safe, $depth, $path);
6bc502cc 1000 }
1001 }
8f0cd6ef 1002
39f65595 1003 return $n+1;
02ebf404 1004}
1005
d8634192 1006/**
1007 * Ensure all courses have a valid course category
1008 * useful if a category has been removed manually
1009 **/
1010function fix_coursecategory_orphans() {
1011
1012 global $CFG;
1013
1014 // Note: the handling of sortorder here is arguably
1015 // open to race conditions. Hard to fix here, unlikely
1016 // to hit anyone in production.
1017
1018 $sql = "SELECT c.id, c.category, c.shortname
1019 FROM {$CFG->prefix}course c
1020 LEFT OUTER JOIN {$CFG->prefix}course_categories cc ON c.category=cc.id
1021 WHERE cc.id IS NULL AND c.id != " . SITEID;
1022
1023 $rs = get_recordset_sql($sql);
1024
1025 if ($rs->RecordCount()){ // we have some orphans
1026
1027 // the "default" category is the lowest numbered...
1028 $default = get_field_sql("SELECT MIN(id)
1029 FROM {$CFG->prefix}course_categories");
1030 $sortorder = get_field_sql("SELECT MAX(sortorder)
1031 FROM {$CFG->prefix}course
1032 WHERE category=$default");
1033
1034
1035 begin_sql();
1036 $tx = true;
1037 while ($tx && $course = rs_fetch_next_record($rs)) {
1038 $tx = $tx && set_field('course', 'category', $default, 'id', $course->id);
1039 $tx = $tx && set_field('course', 'sortorder', ++$sortorder, 'id', $course->id);
1040 }
1041 if ($tx) {
1042 commit_sql();
1043 } else {
1044 rollback_sql();
1045 }
1046 }
1047}
1048
db4b12eb 1049/**
1050 * List of remote courses that a user has access to via MNET.
1051 * Works only on the IDP
1052 *
1053 * @uses $CFG, $USER
1054 * @return array {@link $COURSE} of course objects
1055 */
1056function get_my_remotecourses($userid=0) {
1057 global $CFG, $USER;
1058
1059 if (empty($userid)) {
1060 $userid = $USER->id;
1061 }
1062
5930cded 1063 $sql = "SELECT c.remoteid, c.shortname, c.fullname,
86dd62a7 1064 c.hostid, c.summary, c.cat_name,
1065 h.name AS hostname
db4b12eb 1066 FROM {$CFG->prefix}mnet_enrol_course c
1067 JOIN {$CFG->prefix}mnet_enrol_assignments a ON c.id=a.courseid
86dd62a7 1068 JOIN {$CFG->prefix}mnet_host h ON c.hostid=h.id
db4b12eb 1069 WHERE a.userid={$userid}";
1070
1071 return get_records_sql($sql);
1072}
1073
1074/**
1075 * List of remote hosts that a user has access to via MNET.
1076 * Works on the SP
1077 *
1078 * @uses $CFG, $USER
1079 * @return array of host objects
1080 */
1081function get_my_remotehosts() {
1082 global $CFG, $USER;
1083
1084 if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1085 return false; // Return nothing on the IDP
1086 }
1087 if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1088 return $USER->mnet_foreign_host_array;
1089 }
1090 return false;
1091}
fbc21ae8 1092
18a97fd8 1093/**
fbc21ae8 1094 * This function creates a default separated/connected scale
1095 *
1096 * This function creates a default separated/connected scale
1097 * so there's something in the database. The locations of
1098 * strings and files is a bit odd, but this is because we
1099 * need to maintain backward compatibility with many different
1100 * existing language translations and older sites.
1101 *
1102 * @uses $CFG
1103 */
02ebf404 1104function make_default_scale() {
02ebf404 1105
1106 global $CFG;
1107
1108 $defaultscale = NULL;
1109 $defaultscale->courseid = 0;
1110 $defaultscale->userid = 0;
d4419d55 1111 $defaultscale->name = get_string('separateandconnected');
1112 $defaultscale->scale = get_string('postrating1', 'forum').','.
1113 get_string('postrating2', 'forum').','.
1114 get_string('postrating3', 'forum');
02ebf404 1115 $defaultscale->timemodified = time();
1116
8f0cd6ef 1117 /// Read in the big description from the file. Note this is not
02ebf404 1118 /// HTML (despite the file extension) but Moodle format text.
d4419d55 1119 $parentlang = get_string('parentlang');
ee6e91d4 1120 if (is_readable($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1121 $file = file($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1122 } else if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
d4419d55 1123 $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
ee6e91d4 1124 } else if ($parentlang and is_readable($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1125 $file = file($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
d4419d55 1126 } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1127 $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
ee6e91d4 1128 } else if (is_readable($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html')) {
1129 $file = file($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html');
02ebf404 1130 } else {
d4419d55 1131 $file = '';
02ebf404 1132 }
1133
d4419d55 1134 $defaultscale->description = addslashes(implode('', $file));
02ebf404 1135
d4419d55 1136 if ($defaultscale->id = insert_record('scale', $defaultscale)) {
1137 execute_sql('UPDATE '. $CFG->prefix .'forum SET scale = \''. $defaultscale->id .'\'', false);
02ebf404 1138 }
1139}
1140
fbc21ae8 1141
18a97fd8 1142/**
fbc21ae8 1143 * Returns a menu of all available scales from the site as well as the given course
1144 *
1145 * @uses $CFG
1146 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 1147 * @return object
fbc21ae8 1148 */
02ebf404 1149function get_scales_menu($courseid=0) {
02ebf404 1150
1151 global $CFG;
8f0cd6ef 1152
1153 $sql = "SELECT id, name FROM {$CFG->prefix}scale
1154 WHERE courseid = '0' or courseid = '$courseid'
02ebf404 1155 ORDER BY courseid ASC, name ASC";
1156
d4419d55 1157 if ($scales = get_records_sql_menu($sql)) {
02ebf404 1158 return $scales;
1159 }
1160
1161 make_default_scale();
1162
d4419d55 1163 return get_records_sql_menu($sql);
02ebf404 1164}
1165
5baa0ad6 1166
1167
1168/**
1169 * Given a set of timezone records, put them in the database, replacing what is there
1170 *
1171 * @uses $CFG
1172 * @param array $timezones An array of timezone records
1173 */
1174function update_timezone_records($timezones) {
1175/// Given a set of timezone records, put them in the database
1176
1177 global $CFG;
1178
1179/// Clear out all the old stuff
1180 execute_sql('TRUNCATE TABLE '.$CFG->prefix.'timezone', false);
1181
1182/// Insert all the new stuff
1183 foreach ($timezones as $timezone) {
1184 insert_record('timezone', $timezone);
1185 }
1186}
1187
1188
df28d6c5 1189/// MODULE FUNCTIONS /////////////////////////////////////////////////
1190
18a97fd8 1191/**
fbc21ae8 1192 * Just gets a raw list of all modules in a course
1193 *
1194 * @uses $CFG
1195 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 1196 * @return object
fbc21ae8 1197 */
9fa49e22 1198function get_course_mods($courseid) {
9fa49e22 1199 global $CFG;
1200
3a11c548 1201 if (empty($courseid)) {
1202 return false; // avoid warnings
1203 }
1204
7acaa63d 1205 return get_records_sql("SELECT cm.*, m.name as modname
8f0cd6ef 1206 FROM {$CFG->prefix}modules m,
7acaa63d 1207 {$CFG->prefix}course_modules cm
8f0cd6ef 1208 WHERE cm.course = '$courseid'
9fa49e22 1209 AND cm.module = m.id ");
1210}
1211
fbc21ae8 1212
18a97fd8 1213/**
f9d5371b 1214 * Given an id of a course module, finds the coursemodule description
fbc21ae8 1215 *
f9d5371b 1216 * @param string $modulename name of module type, eg. resource, assignment,...
1217 * @param int $cmid course module id (id in course_modules table)
1218 * @param int $courseid optional course id for extra validation
1219 * @return object course module instance with instance and module name
1220 */
1221function get_coursemodule_from_id($modulename, $cmid, $courseid=0) {
1222
1223 global $CFG;
1224
1225 $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
1226
1227 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1228 FROM {$CFG->prefix}course_modules cm,
1229 {$CFG->prefix}modules md,
1230 {$CFG->prefix}$modulename m
1231 WHERE $courseselect
1232 cm.id = '$cmid' AND
1233 cm.instance = m.id AND
1234 md.name = '$modulename' AND
1235 md.id = cm.module");
1236}
1237
1238/**
1239 * Given an instance number of a module, finds the coursemodule description
1240 *
1241 * @param string $modulename name of module type, eg. resource, assignment,...
1242 * @param int $instance module instance number (id in resource, assignment etc. table)
1243 * @param int $courseid optional course id for extra validation
1244 * @return object course module instance with instance and module name
fbc21ae8 1245 */
b63c0ee5 1246function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
df28d6c5 1247
1248 global $CFG;
f9d5371b 1249
b63c0ee5 1250 $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
df28d6c5 1251
f9d5371b 1252 return get_record_sql("SELECT cm.*, m.name, md.name as modname
8f0cd6ef 1253 FROM {$CFG->prefix}course_modules cm,
1254 {$CFG->prefix}modules md,
1255 {$CFG->prefix}$modulename m
b63c0ee5 1256 WHERE $courseselect
8f0cd6ef 1257 cm.instance = m.id AND
1258 md.name = '$modulename' AND
df28d6c5 1259 md.id = cm.module AND
1260 m.id = '$instance'");
1261
1262}
1263
185cfb09 1264/**
1265 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1266 *
1267 * Returns an array of all the active instances of a particular
1268 * module in given courses, sorted in the order they are defined
1269 * in the course. Returns false on any errors.
1270 *
1271 * @uses $CFG
1272 * @param string $modulename The name of the module to get instances for
613bbd7c 1273 * @param array $courses This depends on an accurate $course->modinfo
1274 * @return array of instances
185cfb09 1275 */
00e12c73 1276function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
185cfb09 1277 global $CFG;
1278 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1279 return array();
1280 }
1281 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode, cm.course
1282 FROM {$CFG->prefix}course_modules cm,
1283 {$CFG->prefix}course_sections cw,
1284 {$CFG->prefix}modules md,
1285 {$CFG->prefix}$modulename m
1286 WHERE cm.course IN (".implode(',',array_keys($courses)).") AND
1287 cm.instance = m.id AND
1288 cm.section = cw.id AND
1289 md.name = '$modulename' AND
1290 md.id = cm.module")) {
1291 return array();
1292 }
1293
1294 $outputarray = array();
1295
1296 foreach ($courses as $course) {
00e12c73 1297 if ($includeinvisible) {
1298 $invisible = -1;
1299 } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id), $userid)) {
1300 // Usually hide non-visible instances from students
185cfb09 1301 $invisible = -1;
1302 } else {
1303 $invisible = 0;
1304 }
fea43a7f 1305
1306 /// Casting $course->modinfo to string prevents one notice when the field is null
1307 if (!$modinfo = unserialize((string)$course->modinfo)) {
185cfb09 1308 continue;
1309 }
1310 foreach ($modinfo as $mod) {
1311 if ($mod->mod == $modulename and $mod->visible > $invisible) {
1312 $instance = $rawmods[$mod->cm];
1313 if (!empty($mod->extra)) {
1314 $instance->extra = $mod->extra;
1315 }
1316 $outputarray[] = $instance;
1317 }
1318 }
1319 }
1320
1321 return $outputarray;
1322
1323}
fbc21ae8 1324
18a97fd8 1325/**
fbc21ae8 1326 * Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined
1327 *
1328 * Returns an array of all the active instances of a particular
1329 * module in a given course, sorted in the order they are defined
1330 * in the course. Returns false on any errors.
1331 *
1332 * @uses $CFG
1333 * @param string $modulename The name of the module to get instances for
1334 * @param object(course) $course This depends on an accurate $course->modinfo
fbc21ae8 1335 */
00e12c73 1336function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
df28d6c5 1337
1338 global $CFG;
1339
3cc8b355 1340 if (empty($course->modinfo)) {
1341 return array();
1342 }
1343
fea43a7f 1344 if (!$modinfo = unserialize((string)$course->modinfo)) {
cccb016a 1345 return array();
1acfbce5 1346 }
1347
d8c9d8a1 1348 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode,cm.groupingid
8f0cd6ef 1349 FROM {$CFG->prefix}course_modules cm,
1350 {$CFG->prefix}course_sections cw,
1351 {$CFG->prefix}modules md,
1352 {$CFG->prefix}$modulename m
1353 WHERE cm.course = '$course->id' AND
1354 cm.instance = m.id AND
8f0cd6ef 1355 cm.section = cw.id AND
1356 md.name = '$modulename' AND
cccb016a 1357 md.id = cm.module")) {
1358 return array();
1359 }
1360
00e12c73 1361 if ($includeinvisible) {
1362 $invisible = -1;
1363 } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id), $userid)) {
1364 // Usually hide non-visible instances from students
cccb016a 1365 $invisible = -1;
1366 } else {
1367 $invisible = 0;
1368 }
1369
78d4711e 1370 $outputarray = array();
1371
cccb016a 1372 foreach ($modinfo as $mod) {
8a67b03f 1373 $mod->id = $mod->cm;
e6839677 1374 $mod->course = $course->id;
8a67b03f 1375 if (!groups_course_module_visible($mod)) {
1376 continue;
1377 }
cccb016a 1378 if ($mod->mod == $modulename and $mod->visible > $invisible) {
7f12f9cd 1379 $instance = $rawmods[$mod->cm];
1380 if (!empty($mod->extra)) {
1381 $instance->extra = $mod->extra;
1382 }
1383 $outputarray[] = $instance;
cccb016a 1384 }
1385 }
1386
1387 return $outputarray;
df28d6c5 1388
1389}
1390
9fa49e22 1391
18a97fd8 1392/**
fbc21ae8 1393 * Determine whether a module instance is visible within a course
1394 *
1395 * Given a valid module object with info about the id and course,
1396 * and the module's type (eg "forum") returns whether the object
1397 * is visible or not
1398 *
1399 * @uses $CFG
613bbd7c 1400 * @param $moduletype Name of the module eg 'forum'
1401 * @param $module Object which is the instance of the module
7290c7fa 1402 * @return bool
fbc21ae8 1403 */
580f2fbc 1404function instance_is_visible($moduletype, $module) {
580f2fbc 1405
1406 global $CFG;
1407
2b49ae96 1408 if (!empty($module->id)) {
e6839677 1409 if ($records = get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.groupmembersonly, cm.course
2b49ae96 1410 FROM {$CFG->prefix}course_modules cm,
1411 {$CFG->prefix}modules m
1412 WHERE cm.course = '$module->course' AND
1413 cm.module = m.id AND
1414 m.name = '$moduletype' AND
1415 cm.instance = '$module->id'")) {
5930cded 1416
2b49ae96 1417 foreach ($records as $record) { // there should only be one - use the first one
13534ef7 1418 return $record->visible && groups_course_module_visible($record);
2b49ae96 1419 }
580f2fbc 1420 }
1421 }
580f2fbc 1422 return true; // visible by default!
1423}
1424
a3fb1c45 1425
1426
1427
9fa49e22 1428/// LOG FUNCTIONS /////////////////////////////////////////////////////
1429
1430
18a97fd8 1431/**
fbc21ae8 1432 * Add an entry to the log table.
1433 *
1434 * Add an entry to the log table. These are "action" focussed rather
1435 * than web server hits, and provide a way to easily reconstruct what
1436 * any particular student has been doing.
1437 *
1438 * @uses $CFG
1439 * @uses $USER
1440 * @uses $db
1441 * @uses $REMOTE_ADDR
1442 * @uses SITEID
89dcb99d 1443 * @param int $courseid The course id
fbc21ae8 1444 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
f7664880 1445 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
fbc21ae8 1446 * @param string $url The file and parameters used to see the results of the action
1447 * @param string $info Additional description information
1448 * @param string $cm The course_module->id if there is one
1449 * @param string $user If log regards $user other than $USER
1450 */
d4419d55 1451function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
e8395a09 1452 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1453 // This is for a good reason: it is the most frequently used DB update function,
1454 // so it has been optimised for speed.
fcaff7ff 1455 global $db, $CFG, $USER;
9fa49e22 1456
7a5b1fc5 1457 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
f78b3c34 1458 $cm = 0;
1459 }
1460
3d94772d 1461 if ($user) {
1462 $userid = $user;
1463 } else {
cb80265b 1464 if (!empty($USER->realuser)) { // Don't log
3d94772d 1465 return;
1466 }
d4419d55 1467 $userid = empty($USER->id) ? '0' : $USER->id;
9fa49e22 1468 }
1469
fcaff7ff 1470 $REMOTE_ADDR = getremoteaddr();
1471
9fa49e22 1472 $timenow = time();
1473 $info = addslashes($info);
10a760b9 1474 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1475 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
1476 }
853df85e 1477
1478 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; $PERF->logwrites++;};
1479
8b497bbc 1480 if ($CFG->type = 'oci8po') {
1481 if (empty($info)) {
1482 $info = ' ';
1483 }
1484 }
1485
d4419d55 1486 $result = $db->Execute('INSERT INTO '. $CFG->prefix .'log (time, userid, course, ip, module, cmid, action, url, info)
1487 VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')");
ebc3bd2b 1488
ea82d6b6 1489 if (!$result and debugging()) {
d4419d55 1490 echo '<p>Error: Could not insert a new entry to the Moodle log</p>'; // Don't throw an error
8f0cd6ef 1491 }
cb80265b 1492
7c3dab9f 1493/// Store lastaccess times for the current user, do not use in cron and other commandline scripts
a9fcd13a 1494/// only update the lastaccess/timeaccess fields only once every 60s
7c3dab9f 1495 if (!empty($USER->id) && ($userid == $USER->id) && !defined('FULLME')) {
5930cded 1496 $db->Execute('UPDATE '. $CFG->prefix .'user
cb80265b 1497 SET lastip=\''. $REMOTE_ADDR .'\', lastaccess=\''. $timenow .'\'
a9fcd13a 1498 WHERE id = \''. $userid .'\' AND '.$timenow.' - lastaccess > 60');
cb80265b 1499 if ($courseid != SITEID && !empty($courseid)) {
853df85e 1500 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
5930cded 1501
a9fcd13a 1502 if ($ulid = get_field('user_lastaccess', 'id', 'userid', $userid, 'courseid', $courseid)) {
1503 $db->Execute("UPDATE {$CFG->prefix}user_lastaccess
1504 SET timeaccess=$timenow
1505 WHERE id = $ulid AND $timenow - timeaccess > 60");
cb80265b 1506 } else {
a9fcd13a 1507 $db->Execute("INSERT INTO {$CFG->prefix}user_lastaccess
1508 ('userid', 'courseid', 'timeaccess')
1509 VALUES ($userid, $courseid, $timenow)");
114176a2 1510 }
a9fcd13a 1511 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
3d94772d 1512 }
8f0cd6ef 1513 }
9fa49e22 1514}
1515
1516
18a97fd8 1517/**
fbc21ae8 1518 * Select all log records based on SQL criteria
1519 *
1520 * @uses $CFG
1521 * @param string $select SQL select criteria
1522 * @param string $order SQL order by clause to sort the records returned
1523 * @param string $limitfrom ?
1524 * @param int $limitnum ?
1525 * @param int $totalcount Passed in by reference.
7290c7fa 1526 * @return object
fbc21ae8 1527 * @todo Finish documenting this function
1528 */
d4419d55 1529function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
9fa49e22 1530 global $CFG;
1531
519d369f 1532 if ($order) {
d4419d55 1533 $order = 'ORDER BY '. $order;
519d369f 1534 }
1535
fbc21ae8 1536 $selectsql = $CFG->prefix .'log l LEFT JOIN '. $CFG->prefix .'user u ON l.userid = u.id '. ((strlen($select) > 0) ? 'WHERE '. $select : '');
a2ddd957 1537 $countsql = $CFG->prefix.'log l '.((strlen($select) > 0) ? ' WHERE '. $select : '');
1538
1539 $totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql");
519d369f 1540
d4419d55 1541 return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture
93a89227 1542 FROM '. $selectsql .' '. $order, $limitfrom, $limitnum) ;
9fa49e22 1543}
1544
519d369f 1545
18a97fd8 1546/**
fbc21ae8 1547 * Select all log records for a given course and user
1548 *
1549 * @uses $CFG
2f87145b 1550 * @uses DAYSECS
fbc21ae8 1551 * @param int $userid The id of the user as found in the 'user' table.
1552 * @param int $courseid The id of the course as found in the 'course' table.
1553 * @param string $coursestart ?
1554 * @todo Finish documenting this function
1555 */
9fa49e22 1556function get_logs_usercourse($userid, $courseid, $coursestart) {
1557 global $CFG;
1558
da0c90c3 1559 if ($courseid) {
d4419d55 1560 $courseselect = ' AND course = \''. $courseid .'\' ';
2700d113 1561 } else {
1562 $courseselect = '';
da0c90c3 1563 }
1564
1604a0fc 1565 return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS .") as day, count(*) as num
8f0cd6ef 1566 FROM {$CFG->prefix}log
1567 WHERE userid = '$userid'
1604a0fc 1568 AND time > '$coursestart' $courseselect
9fa49e22 1569 GROUP BY day ");
1570}
1571
18a97fd8 1572/**
fbc21ae8 1573 * Select all log records for a given course, user, and day
1574 *
1575 * @uses $CFG
2f87145b 1576 * @uses HOURSECS
fbc21ae8 1577 * @param int $userid The id of the user as found in the 'user' table.
1578 * @param int $courseid The id of the course as found in the 'course' table.
1579 * @param string $daystart ?
7290c7fa 1580 * @return object
fbc21ae8 1581 * @todo Finish documenting this function
1582 */
9fa49e22 1583function get_logs_userday($userid, $courseid, $daystart) {
1584 global $CFG;
1585
7e4a6488 1586 if ($courseid) {
d4419d55 1587 $courseselect = ' AND course = \''. $courseid .'\' ';
2700d113 1588 } else {
1589 $courseselect = '';
7e4a6488 1590 }
1591
1604a0fc 1592 return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS .") as hour, count(*) as num
9fa49e22 1593 FROM {$CFG->prefix}log
8f0cd6ef 1594 WHERE userid = '$userid'
1604a0fc 1595 AND time > '$daystart' $courseselect
9fa49e22 1596 GROUP BY hour ");
1597}
1598
b4bac9b6 1599/**
1600 * Returns an object with counts of failed login attempts
1601 *
8f0cd6ef 1602 * Returns information about failed login attempts. If the current user is
1603 * an admin, then two numbers are returned: the number of attempts and the
b4bac9b6 1604 * number of accounts. For non-admins, only the attempts on the given user
1605 * are shown.
1606 *
fbc21ae8 1607 * @param string $mode Either 'admin', 'teacher' or 'everybody'
1608 * @param string $username The username we are searching for
1609 * @param string $lastlogin The date from which we are searching
1610 * @return int
b4bac9b6 1611 */
b4bac9b6 1612function count_login_failures($mode, $username, $lastlogin) {
1613
d4419d55 1614 $select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin;
b4bac9b6 1615
51792df0 1616 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM, SITEID))) { // Return information about all accounts
b4bac9b6 1617 if ($count->attempts = count_records_select('log', $select)) {
1618 $count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)');
1619 return $count;
1620 }
9407d456 1621 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
d4419d55 1622 if ($count->attempts = count_records_select('log', $select .' AND info = \''. $username .'\'')) {
b4bac9b6 1623 return $count;
1624 }
1625 }
1626 return NULL;
1627}
1628
1629
a3fb1c45 1630/// GENERAL HELPFUL THINGS ///////////////////////////////////
1631
18a97fd8 1632/**
fbc21ae8 1633 * Dump a given object's information in a PRE block.
1634 *
1635 * Mostly just used for debugging.
1636 *
1637 * @param mixed $object The data to be printed
fbc21ae8 1638 */
a3fb1c45 1639function print_object($object) {
1aa7b31d 1640 echo '<pre class="notifytiny">' . htmlspecialchars(print_r($object,true)) . '</pre>';
a3fb1c45 1641}
1642
0986271b 1643function course_parent_visible($course = null) {
fa145ae1 1644 global $CFG;
1645
418b4e5a 1646 if (empty($course)) {
1647 return true;
1648 }
1649 if (!empty($CFG->allowvisiblecoursesinhiddencategories)) {
1650 return true;
1651 }
0986271b 1652 return category_parent_visible($course->category);
1653}
1654
1655function category_parent_visible($parent = 0) {
5930cded 1656
824f1c40 1657 static $visible;
1658
0986271b 1659 if (!$parent) {
1660 return true;
1661 }
5930cded 1662
824f1c40 1663 if (empty($visible)) {
1664 $visible = array(); // initialize
1665 }
1666
1667 if (array_key_exists($parent,$visible)) {
1668 return $visible[$parent];
1669 }
5930cded 1670
0986271b 1671 $category = get_record('course_categories', 'id', $parent);
1672 $list = explode('/', preg_replace('/^\/(.*)$/', '$1', $category->path));
1673 $list[] = $parent;
1674 $parents = get_records_list('course_categories', 'id', implode(',', $list), 'depth DESC');
824f1c40 1675 $v = true;
1676 foreach ($parents as $p) {
1677 if (!$p->visible) {
1678 $v = false;
0986271b 1679 }
1680 }
824f1c40 1681 $visible[$parent] = $v; // now cache it
1682 return $v;
0986271b 1683}
1684
62d4e774 1685/**
5930cded 1686 * This function is the official hook inside XMLDB stuff to delegate its debug to one
62d4e774 1687 * external function.
1688 *
1689 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1690 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1691 *
1692 * @param $message string contains the error message
1693 * @param $object object XMLDB object that fired the debug
1694 */
1695function xmldb_debug($message, $object) {
1696
92b564f4 1697 debugging($message, DEBUG_DEVELOPER);
62d4e774 1698}
1699
49860445 1700/**
1701 * Get the lists of courses the current user has $cap capability in
5930cded 1702 * I am not sure if this is needed, it loops through all courses so
1703 * could cause performance problems.
1704 * If it's not used, we can use a faster function to detect
49860445 1705 * capability in restorelib.php
1706 * @param string $cap
1707 * @return array
1708 */
1709function get_capability_courses($cap) {
1710 global $USER;
5930cded 1711
49860445 1712 $mycourses = array();
1713 if ($courses = get_records('course')) {
1714 foreach ($courses as $course) {
1715 if (has_capability($cap, get_context_instance(CONTEXT_COURSE, $course->id))) {
5930cded 1716 $mycourses[] = $course->id;
49860445 1717 }
1718 }
1719 }
5930cded 1720
49860445 1721 return $mycourses;
5930cded 1722}
1723
49860445 1724/**
1725 * true or false function to see if user can create any courses at all
1726 * @return bool
1727 */
1728function user_can_create_courses() {
1729 global $USER;
1730 // if user has course creation capability at any site or course cat, then return true;
5930cded 1731
49860445 1732 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
5930cded 1733 return true;
49860445 1734 } else {
5930cded 1735 return (bool) count(get_creatable_categories());
49860445 1736 }
5930cded 1737
49860445 1738}
1739
1740/**
1741 * get the list of categories the current user can create courses in
1742 * @return array
1743 */
1744function get_creatable_categories() {
5930cded 1745
49860445 1746 $creatablecats = array();
1747 if ($cats = get_records('course_categories')) {
1748 foreach ($cats as $cat) {
1749 if (has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $cat->id))) {
1750 $creatablecats[$cat->id] = $cat->name;
1751 }
1752 }
1753 }
1754 return $creatablecats;
1755}
1756
41883f79 1757/**
1758 * Turn an array of ints into a string usable in an IN sql clause...
1759 *
1760 **/
1761function sql_intarray_to_in($array) {
1762
1763 $na = array();
1764 $c = count($array);
1765 for ($n=0;$n<$c;$n++) {
1766 if (isset($array[$n]) && is_int($array[$n])) {
1767 $na[] = $array[$n];
1768 }
1769 }
1770 return join(',',$array);
1771}
1772
9d5b689c 1773// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
03517306 1774?>