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