mnet: it is $USER->mnet_foreign_host_array instead of $SESSION->mnet_foreign_host_arr...
[moodle.git] / lib / datalib.php
CommitLineData
6078ba30 1<?php // $Id$
7cf1c7bd 2
3/**
4 * Library of functions for database manipulation.
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
11a052a6 16/**
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;
20aeb4b8 65
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
20aeb4b8 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);
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" : "");
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 *
119 * If $coursid specifies the site course then this function searches
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 ?
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,
f3f7610c
ML
163 ".groups_members_from_sql()."
164 WHERE $select AND ".groups_members_where_sql($groupid, '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;
36075e09 217
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
6bff0453 228 $select = 'username <> \'guest\' AND username <> \'changeme\' 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
6bff0453 283 $select = "deleted <> '1' AND username <> 'changeme'";
488acd1b 284
0044147e 285 if (!empty($search)) {
286 $search = trim($search);
488acd1b 287 $select .= " AND ($fullname $LIKE '%$search%' OR email $LIKE '%$search%') ";
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
8f0cd6ef 324 AND username <> 'guest'
9fa49e22 325 AND username <> 'changeme'");
326}
327
328
18a97fd8 329/**
7290c7fa 330 * Full list of users that have not yet confirmed their accounts.
fbc21ae8 331 *
332 * @uses $CFG
333 * @param string $cutofftime ?
7290c7fa 334 * @return object {@link $USER} records
fbc21ae8 335 */
99988d1a 336function get_users_unconfirmed($cutofftime=2000000000) {
9fa49e22 337 global $CFG;
8f0cd6ef 338 return get_records_sql("SELECT *
339 FROM {$CFG->prefix}user
9fa49e22 340 WHERE confirmed = 0
8f0cd6ef 341 AND firstaccess > 0
cf36da64 342 AND firstaccess < $cutofftime");
9fa49e22 343}
344
613bbd7c 345/**
346 * All users that we have not seen for a really long time (ie dead accounts)
347 *
348 * @uses $CFG
349 * @param string $cutofftime ?
350 * @return object {@link $USER} records
613bbd7c 351 */
352function get_users_longtimenosee($cutofftime) {
353 global $CFG;
cc7c0592 354 return get_records_sql("SELECT userid as id, courseid
355 FROM {$CFG->prefix}user_lastaccess
cf36da64 356 WHERE courseid != ".SITEID."
357 AND timeaccess > 0
358 AND timeaccess < $cutofftime ");
613bbd7c 359}
9fa49e22 360
fa22fd5f 361/**
362 * Full list of bogus accounts that are probably not ever going to be used
363 *
364 * @uses $CFG
365 * @param string $cutofftime ?
366 * @return object {@link $USER} records
fa22fd5f 367 */
368
369function get_users_not_fully_set_up($cutofftime=2000000000) {
370 global $CFG;
371 return get_records_sql("SELECT *
372 FROM {$CFG->prefix}user
373 WHERE confirmed = 1
374 AND lastaccess > 0
cf36da64 375 AND lastaccess < $cutofftime
fa22fd5f 376 AND deleted = 0
377 AND (lastname = '' OR firstname = '' OR email = '')");
378}
379
380
f3f7610c
ML
381/** TODO: functions now in /group/lib/legacylib.php (3)
382get_groups
383get_group_users
384user_group
385
fbc21ae8 386 * Returns an array of group objects that the user is a member of
387 * in the given course. If userid isn't specified, then return a
388 * list of all groups in the course.
389 *
390 * @uses $CFG
89dcb99d 391 * @param int $courseid The id of the course in question.
fbc21ae8 392 * @param int $userid The id of the user in question as found in the 'user' table 'id' field.
7290c7fa 393 * @return object
f3f7610c 394 *
f374fb10 395function get_groups($courseid, $userid=0) {
396 global $CFG;
397
398 if ($userid) {
d4419d55 399 $dbselect = ', '. $CFG->prefix .'groups_members m';
400 $userselect = 'AND m.groupid = g.id AND m.userid = \''. $userid .'\'';
2d439c9d 401 } else {
402 $dbselect = '';
403 $userselect = '';
f374fb10 404 }
405
94ef00f3 406 return get_records_sql("SELECT g.*
2d439c9d 407 FROM {$CFG->prefix}groups g $dbselect
f374fb10 408 WHERE g.courseid = '$courseid' $userselect ");
409}
410
411
412/**
613bbd7c 413 * Returns an array of user objects that belong to a given group
fbc21ae8 414 *
415 * @uses $CFG
416 * @param int $groupid The group in question.
417 * @param string $sort ?
418 * @param string $exceptions ?
7290c7fa 419 * @return object
f3f7610c 420 *
49668367 421function get_group_users($groupid, $sort='u.lastaccess DESC', $exceptions='', $fields='u.*') {
f374fb10 422 global $CFG;
900df8b6 423 if (!empty($exceptions)) {
d4419d55 424 $except = ' AND u.id NOT IN ('. $exceptions .') ';
900df8b6 425 } else {
426 $except = '';
427 }
c1147b7e 428 // in postgres, you can't have things in sort that aren't in the select, so...
429 $extrafield = str_replace('ASC','',$sort);
d5efb299 430 $extrafield = str_replace('DESC','',$extrafield);
c1147b7e 431 $extrafield = trim($extrafield);
432 if (!empty($extrafield)) {
433 $extrafield = ','.$extrafield;
434 }
82749af7 435 return get_records_sql("SELECT $fields $extrafield
f374fb10 436 FROM {$CFG->prefix}user u,
8f0cd6ef 437 {$CFG->prefix}groups_members m
f374fb10 438 WHERE m.groupid = '$groupid'
900df8b6 439 AND m.userid = u.id $except
2c4263c4 440 ORDER BY $sort");
f374fb10 441}
442
f374fb10 443/**
fbc21ae8 444 * Returns the user's group in a particular course
445 *
446 * @uses $CFG
447 * @param int $courseid The course in question.
448 * @param int $userid The id of the user as found in the 'user' table.
fa22fd5f 449 * @param int $groupid The id of the group the user is in.
7290c7fa 450 * @return object
f3f7610c 451 *
f374fb10 452function user_group($courseid, $userid) {
453 global $CFG;
454
fa22fd5f 455 return get_records_sql("SELECT g.*
0da33e07 456 FROM {$CFG->prefix}groups g,
457 {$CFG->prefix}groups_members m
f374fb10 458 WHERE g.courseid = '$courseid'
459 AND g.id = m.groupid
fa22fd5f 460 AND m.userid = '$userid'
461 ORDER BY name ASC");
f374fb10 462}
f3f7610c 463*/
f374fb10 464
9fa49e22 465
02ebf404 466
467/// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
468
469
18a97fd8 470/**
fbc21ae8 471 * Returns $course object of the top-level site.
472 *
89dcb99d 473 * @return course A {@link $COURSE} object for the site
fbc21ae8 474 */
c44d5d42 475function get_site() {
476
477 global $SITE;
478
479 if (!empty($SITE->id)) { // We already have a global to use, so return that
480 return $SITE;
481 }
02ebf404 482
c44d5d42 483 if ($course = get_record('course', 'category', 0)) {
02ebf404 484 return $course;
485 } else {
486 return false;
487 }
488}
489
18a97fd8 490/**
613bbd7c 491 * Returns list of courses, for whole site, or category
492 *
493 * Returns list of courses, for whole site, or category
494 * Important: Using c.* for fields is extremely expensive because
495 * we are using distinct. You almost _NEVER_ need all the fields
496 * in such a large SELECT
497 *
498 * @param type description
499 *
613bbd7c 500 */
6315b1c8 501function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
02ebf404 502
8ef9cb56 503 global $USER, $CFG;
6315b1c8 504
6315b1c8 505 if ($categoryid != "all" && is_numeric($categoryid)) {
71dea306 506 $categoryselect = "WHERE c.category = '$categoryid'";
507 } else {
508 $categoryselect = "";
09575480 509 }
510
511 if (empty($sort)) {
512 $sortstatement = "";
513 } else {
514 $sortstatement = "ORDER BY $sort";
515 }
516
517 $visiblecourses = array();
71dea306 518
519 // pull out all course matching the cat
09575480 520 if ($courses = get_records_sql("SELECT $fields
71dea306 521 FROM {$CFG->prefix}course c
522 $categoryselect
09575480 523 $sortstatement")) {
524
525 // loop throught them
526 foreach ($courses as $course) {
527
285f94f5 528 if (isset($course->visible) && $course->visible <= 0) {
09575480 529 // for hidden courses, require visibility check
285f94f5 530 if (has_capability('moodle/course:viewhiddencourses',
531 get_context_instance(CONTEXT_COURSE, $course->id))) {
09575480 532 $visiblecourses [] = $course;
533 }
534 } else {
71dea306 535 $visiblecourses [] = $course;
09575480 536 }
537 }
6315b1c8 538 }
71dea306 539 return $visiblecourses;
6315b1c8 540
71dea306 541/*
6315b1c8 542 $teachertable = "";
543 $visiblecourses = "";
544 $sqland = "";
545 if (!empty($categoryselect)) {
546 $sqland = "AND ";
547 }
548 if (!empty($USER->id)) { // May need to check they are a teacher
ae9e4c06 549 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
6315b1c8 550 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
551 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course = c.id";
552 }
553 } else {
554 $visiblecourses = "$sqland c.visible > 0";
8ef9cb56 555 }
556
6315b1c8 557 if ($categoryselect or $visiblecourses) {
558 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
14f32609 559 } else {
6315b1c8 560 $selectsql = "{$CFG->prefix}course c $teachertable";
14f32609 561 }
562
5b66416f 563 $extrafield = str_replace('ASC','',$sort);
564 $extrafield = str_replace('DESC','',$extrafield);
565 $extrafield = trim($extrafield);
566 if (!empty($extrafield)) {
567 $extrafield = ','.$extrafield;
568 }
569 return get_records_sql("SELECT ".((!empty($teachertable)) ? " DISTINCT " : "")." $fields $extrafield FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : ""));
71dea306 570 */
8130b77b 571}
572
8130b77b 573
6315b1c8 574/**
613bbd7c 575 * Returns list of courses, for whole site, or category
576 *
577 * Similar to get_courses, but allows paging
578 * Important: Using c.* for fields is extremely expensive because
579 * we are using distinct. You almost _NEVER_ need all the fields
580 * in such a large SELECT
581 *
582 * @param type description
583 *
613bbd7c 584 */
6315b1c8 585function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
586 &$totalcount, $limitfrom="", $limitnum="") {
c7fe5c6f 587
8130b77b 588 global $USER, $CFG;
71dea306 589
590 $categoryselect = "";
591 if ($categoryid != "all" && is_numeric($categoryid)) {
592 $categoryselect = "WHERE c.category = '$categoryid'";
593 } else {
594 $categoryselect = "";
595 }
596
597 // pull out all course matching the cat
12490fc2 598 $visiblecourses = array();
599 if (!($courses = get_records_sql("SELECT $fields
71dea306 600 FROM {$CFG->prefix}course c
601 $categoryselect
12490fc2 602 ORDER BY $sort"))) {
603 return $visiblecourses;
604 }
71dea306 605 $totalcount = 0;
606
607 if (!$limitnum) {
608 $limitnum = count($courses);
609 }
610
285f94f5 611 if (!$limitfrom) {
71dea306 612 $limitfrom = 0;
613 }
614
615 // iteration will have to be done inside loop to keep track of the limitfrom and limitnum
616 foreach ($courses as $course) {
617 if ($course->visible <= 0) {
618 // for hidden courses, require visibility check
619 if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
620 $totalcount++;
621 if ($totalcount > $limitfrom && count($visiblecourses) < $limitnum) {
622 $visiblecourses [] = $course;
623 }
624 }
625 } else {
626 $totalcount++;
627 if ($totalcount > $limitfrom && count($visiblecourses) < $limitnum) {
628 $visiblecourses [] = $course;
629 }
630 }
631 }
632
633 return $visiblecourses;
634
635/**
8130b77b 636
6315b1c8 637 $categoryselect = "";
b565bbdf 638 if ($categoryid != "all" && is_numeric($categoryid)) {
6315b1c8 639 $categoryselect = "c.category = '$categoryid'";
8130b77b 640 }
641
6315b1c8 642 $teachertable = "";
643 $visiblecourses = "";
644 $sqland = "";
645 if (!empty($categoryselect)) {
646 $sqland = "AND ";
c7fe5c6f 647 }
2d2da684 648 if (!empty($USER) and !empty($USER->id)) { // May need to check they are a teacher
ae9e4c06 649 if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID))) {
6315b1c8 650 $visiblecourses = "$sqland ((c.visible > 0) OR t.userid = '$USER->id')";
651 $teachertable = "LEFT JOIN {$CFG->prefix}user_teachers t ON t.course=c.id";
652 }
8130b77b 653 } else {
6315b1c8 654 $visiblecourses = "$sqland c.visible > 0";
8130b77b 655 }
656
6315b1c8 657 if ($limitfrom !== "") {
29daf3a0 658 $limit = sql_paging_limit($limitfrom, $limitnum);
6315b1c8 659 } else {
660 $limit = "";
02ebf404 661 }
8ef9cb56 662
6315b1c8 663 $selectsql = "{$CFG->prefix}course c $teachertable WHERE $categoryselect $visiblecourses";
8ef9cb56 664
6315b1c8 665 $totalcount = count_records_sql("SELECT COUNT(DISTINCT c.id) FROM $selectsql");
8ef9cb56 666
2338ad32 667 return get_records_sql("SELECT $fields FROM $selectsql ".((!empty($sort)) ? "ORDER BY $sort" : "")." $limit");
71dea306 668 */
02ebf404 669}
670
671
18a97fd8 672/**
f8e1c7af 673 * List of courses that a user has access to view. Note that for admins,
674 * this usually includes every course on the system.
fbc21ae8 675 *
676 * @uses $CFG
7290c7fa 677 * @param int $userid The user of interest
33f85740 678 * @param string $sort the sortorder in the course table
679 * @param string $fields the fields to return
f8e1c7af 680 * @param bool $doanything True if using the doanything flag
681 * @param int $limit Maximum number of records to return, or 0 for unlimited
33f85740 682 * @return array {@link $COURSE} of course objects
fbc21ae8 683 */
f8e1c7af 684function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields='*', $doanything=false,$limit=0) {
2f3499b7 685
61b03dc7 686 $mycourses = array();
f8e1c7af 687
688 // Fix fields to refer to the course table c
689 $fields=preg_replace('/([a-z0-9*]+)/','c.$1',$fields);
2f3499b7 690
f8e1c7af 691 // Attempt to filter the list of courses in order to reduce the number
692 // of queries in the next part.
693
694 // Check root permissions
695 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
696 if(has_capability('moodle/course:view',$sitecontext,$userid,$doanything)) {
697 // User can view all courses, although there might be exceptions
698 // which we will filter later.
699 $rs = get_recordset('course c', '', '', $sort, $fields);
700 } else {
701 // The only other context level above courses that applies to moodle/course:view
702 // is category. So we consider:
703 // 1. All courses in which the user is assigned a role
704 // 2. All courses in categories in which the user is assigned a role
705 // 3. All courses which have overrides for moodle/course:view
706 // Remember that this is just a filter. We check each individual course later.
707 // However for a typical student on a large system this can reduce the
708 // number of courses considered from around 2,000 to around 2, with corresponding
709 // reduction in the number of queries needed.
710 global $CFG;
711 $rs=get_recordset_sql("
712SELECT
713 $fields
714FROM
715 {$CFG->prefix}role_assignments ra
716 INNER JOIN {$CFG->prefix}context x ON x.id=ra.contextid
717 INNER JOIN {$CFG->prefix}course c ON x.instanceid=c.id AND x.contextlevel=50
718WHERE
719 ra.userid=$userid
720UNION
721SELECT
722 $fields
723FROM
724 {$CFG->prefix}role_assignments ra
725 INNER JOIN {$CFG->prefix}context x ON x.id=ra.contextid
726 INNER JOIN {$CFG->prefix}course_categories a ON x.instanceid=a.id AND x.contextlevel=40
727 INNER JOIN {$CFG->prefix}course c ON c.category=a.id
728WHERE
729 ra.userid=$userid
730UNION
731SELECT
732 $fields
733FROM
734 {$CFG->prefix}role_capabilities ca
735 INNER JOIN {$CFG->prefix}context x ON x.id=ca.contextid AND x.contextlevel=50
736 INNER JOIN {$CFG->prefix}course c ON c.id=x.instanceid
737WHERE
738 ca.contextid <> {$sitecontext->id} AND ca.capability='moodle/course:view'
739ORDER BY $sort");
740 }
0dde27bb 741
742 if ($rs && $rs->RecordCount() > 0) {
743 while (!$rs->EOF) {
744 $course = (object)$rs->fields;
745
746 if ($course->id != SITEID) {
747 // users with moodle/course:view are considered course participants
748 // the course needs to be visible, or user must have moodle/course:viewhiddencourses
749 // capability set to view hidden courses
750 $context = get_context_instance(CONTEXT_COURSE, $course->id);
03bb25e1 751 if ( has_capability('moodle/course:view', $context, $userid, $doanything) &&
81cc8046 752 !has_capability('moodle/legacy:guest', $context, $userid, false) &&
0dde27bb 753 ($course->visible || has_capability('moodle/course:viewhiddencourses', $context, $userid))) {
33f85740 754 $mycourses[$course->id] = $course;
f8e1c7af 755
756 // Only return a limited number of courses if limit is set
757 if($limit>0) {
758 $limit--;
759 if($limit==0) {
760 break;
761 }
762 }
fbcbd77c 763 }
764 }
152a9060 765
0dde27bb 766 $rs->MoveNext();
2f3499b7 767 }
768 }
152a9060 769
0dde27bb 770 return $mycourses;
02ebf404 771}
772
773
18a97fd8 774/**
7290c7fa 775 * A list of courses that match a search
fbc21ae8 776 *
777 * @uses $CFG
778 * @param array $searchterms ?
779 * @param string $sort ?
780 * @param int $page ?
781 * @param int $recordsperpage ?
782 * @param int $totalcount Passed in by reference. ?
7290c7fa 783 * @return object {@link $COURSE} records
fbc21ae8 784 */
d4419d55 785function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
02ebf404 786
787 global $CFG;
788
18a97fd8 789 //to allow case-insensitive search for postgesql
48505662 790 if ($CFG->dbfamily == 'postgres') {
d4419d55 791 $LIKE = 'ILIKE';
792 $NOTLIKE = 'NOT ILIKE'; // case-insensitive
793 $REGEXP = '~*';
794 $NOTREGEXP = '!~*';
02ebf404 795 } else {
d4419d55 796 $LIKE = 'LIKE';
797 $NOTLIKE = 'NOT LIKE';
798 $REGEXP = 'REGEXP';
799 $NOTREGEXP = 'NOT REGEXP';
02ebf404 800 }
801
d4419d55 802 $fullnamesearch = '';
803 $summarysearch = '';
02ebf404 804
02ebf404 805 foreach ($searchterms as $searchterm) {
6bb0f67f 806
807 /// Under Oracle and MSSQL, trim the + and - operators and perform
808 /// simpler LIKE search
48505662 809 if ($CFG->dbfamily == 'oracle' || $CFG->dbfamily == 'mssql') {
6bb0f67f 810 $searchterm = trim($searchterm, '+-');
811 }
812
02ebf404 813 if ($fullnamesearch) {
d4419d55 814 $fullnamesearch .= ' AND ';
02ebf404 815 }
02ebf404 816 if ($summarysearch) {
d4419d55 817 $summarysearch .= ' AND ';
02ebf404 818 }
a8b56716 819
d4419d55 820 if (substr($searchterm,0,1) == '+') {
a8b56716 821 $searchterm = substr($searchterm,1);
822 $summarysearch .= " summary $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
823 $fullnamesearch .= " fullname $REGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
824 } else if (substr($searchterm,0,1) == "-") {
825 $searchterm = substr($searchterm,1);
826 $summarysearch .= " summary $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
827 $fullnamesearch .= " fullname $NOTREGEXP '(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)' ";
828 } else {
d4419d55 829 $summarysearch .= ' summary '. $LIKE .'\'%'. $searchterm .'%\' ';
830 $fullnamesearch .= ' fullname '. $LIKE .'\'%'. $searchterm .'%\' ';
a8b56716 831 }
832
02ebf404 833 }
834
d4419d55 835 $selectsql = $CFG->prefix .'course WHERE ('. $fullnamesearch .' OR '. $summarysearch .') AND category > \'0\'';
a8b56716 836
d4419d55 837 $totalcount = count_records_sql('SELECT COUNT(*) FROM '. $selectsql);
02ebf404 838
422770d8 839 $courses = get_records_sql('SELECT * FROM '. $selectsql .' ORDER BY '. $sort, $page, $recordsperpage);
02ebf404 840
841 if ($courses) { /// Remove unavailable courses from the list
842 foreach ($courses as $key => $course) {
152a9060 843 if (!$course->visible) {
1c45e42e 844 if (!has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
02ebf404 845 unset($courses[$key]);
a8b56716 846 $totalcount--;
02ebf404 847 }
848 }
849 }
850 }
851
852 return $courses;
853}
854
855
18a97fd8 856/**
fbc21ae8 857 * Returns a sorted list of categories
858 *
613bbd7c 859 * @param string $parent The parent category if any
860 * @param string $sort the sortorder
861 * @return array of categories
fbc21ae8 862 */
d4419d55 863function get_categories($parent='none', $sort='sortorder ASC') {
02ebf404 864
814748c9 865 if ($parent === 'none') {
d4419d55 866 $categories = get_records('course_categories', '', '', $sort);
02ebf404 867 } else {
d4419d55 868 $categories = get_records('course_categories', 'parent', $parent, $sort);
02ebf404 869 }
870 if ($categories) { /// Remove unavailable categories from the list
ae9e4c06 871 $creator = has_capability('moodle/course:create', get_context_instance(CONTEXT_SYSTEM, SITEID));
02ebf404 872 foreach ($categories as $key => $category) {
152a9060 873 if (!$category->visible) {
3af6e1db 874 if (!$creator) {
02ebf404 875 unset($categories[$key]);
876 }
877 }
878 }
879 }
880 return $categories;
881}
882
883
18a97fd8 884/**
ba87a4da 885* This recursive function makes sure that the courseorder is consecutive
886*
887* @param type description
888*
889* $n is the starting point, offered only for compatilibity -- will be ignored!
890* $safe (bool) prevents it from assuming category-sortorder is unique, used to upgrade
891* safely from 1.4 to 1.5
892*/
f41ef63e 893function fix_course_sortorder($categoryid=0, $n=0, $safe=0, $depth=0, $path='') {
894
ba87a4da 895 global $CFG;
8f0cd6ef 896
02ebf404 897 $count = 0;
ba87a4da 898
f41ef63e 899 $catgap = 1000; // "standard" category gap
900 $tolerance = 200; // how "close" categories can get
901
902 if ($categoryid > 0){
903 // update depth and path
904 $cat = get_record('course_categories', 'id', $categoryid);
905 if ($cat->parent == 0) {
906 $depth = 0;
907 $path = '';
908 } else if ($depth == 0 ) { // doesn't make sense; get from DB
909 // this is only called if the $depth parameter looks dodgy
910 $parent = get_record('course_categories', 'id', $cat->parent);
911 $path = $parent->path;
912 $depth = $parent->depth;
913 }
914 $path = $path . '/' . $categoryid;
915 $depth = $depth + 1;
ba87a4da 916
f41ef63e 917 set_field('course_categories', 'path', addslashes($path), 'id', $categoryid);
918 set_field('course_categories', 'depth', $depth, 'id', $categoryid);
919 }
39f65595 920
921 // get some basic info about courses in the category
ba87a4da 922 $info = get_record_sql('SELECT MIN(sortorder) AS min,
923 MAX(sortorder) AS max,
f41ef63e 924 COUNT(sortorder) AS count
ba87a4da 925 FROM ' . $CFG->prefix . 'course
926 WHERE category=' . $categoryid);
927 if (is_object($info)) { // no courses?
928 $max = $info->max;
929 $count = $info->count;
930 $min = $info->min;
931 unset($info);
932 }
933
814748c9 934 if ($categoryid > 0 && $n==0) { // only passed category so don't shift it
935 $n = $min;
936 }
937
39f65595 938 // $hasgap flag indicates whether there's a gap in the sequence
939 $hasgap = false;
940 if ($max-$min+1 != $count) {
941 $hasgap = true;
942 }
943
944 // $mustshift indicates whether the sequence must be shifted to
945 // meet its range
946 $mustshift = false;
947 if ($min < $n+$tolerance || $min > $n+$tolerance+$catgap ) {
948 $mustshift = true;
949 }
950
ba87a4da 951 // actually sort only if there are courses,
952 // and we meet one ofthe triggers:
953 // - safe flag
954 // - they are not in a continuos block
955 // - they are too close to the 'bottom'
39f65595 956 if ($count && ( $safe || $hasgap || $mustshift ) ) {
957 // special, optimized case where all we need is to shift
958 if ( $mustshift && !$safe && !$hasgap) {
959 $shift = $n + $catgap - $min;
960 // UPDATE course SET sortorder=sortorder+$shift
961 execute_sql("UPDATE {$CFG->prefix}course
962 SET sortorder=sortorder+$shift
963 WHERE category=$categoryid", 0);
964 $n = $n + $catgap + $count;
965
966 } else { // do it slowly
967 $n = $n + $catgap;
968 // if the new sequence overlaps the current sequence, lack of transactions
969 // will stop us -- shift things aside for a moment...
48505662 970 if ($safe || ($n >= $min && $n+$count+1 < $min && $CFG->dbfamily==='mysql')) {
d6a49dab 971 $shift = $max + $n + 1000;
39f65595 972 execute_sql("UPDATE {$CFG->prefix}course
973 SET sortorder=sortorder+$shift
974 WHERE category=$categoryid", 0);
ba87a4da 975 }
976
39f65595 977 $courses = get_courses($categoryid, 'c.sortorder ASC', 'c.id,c.sortorder');
978 begin_sql();
ba87a4da 979 foreach ($courses as $course) {
980 if ($course->sortorder != $n ) { // save db traffic
981 set_field('course', 'sortorder', $n, 'id', $course->id);
982 }
983 $n++;
984 }
985 commit_sql();
986 }
02ebf404 987 }
d4419d55 988 set_field('course_categories', 'coursecount', $count, 'id', $categoryid);
8f0cd6ef 989
814748c9 990 // $n could need updating
991 $max = get_field_sql("SELECT MAX(sortorder) from {$CFG->prefix}course WHERE category=$categoryid");
992 if ($max > $n) {
993 $n = $max;
994 }
758b9a4d 995
6bc502cc 996 if ($categories = get_categories($categoryid)) {
997 foreach ($categories as $category) {
f41ef63e 998 $n = fix_course_sortorder($category->id, $n, $safe, $depth, $path);
6bc502cc 999 }
1000 }
8f0cd6ef 1001
39f65595 1002 return $n+1;
02ebf404 1003}
1004
fbc21ae8 1005
18a97fd8 1006/**
fbc21ae8 1007 * This function creates a default separated/connected scale
1008 *
1009 * This function creates a default separated/connected scale
1010 * so there's something in the database. The locations of
1011 * strings and files is a bit odd, but this is because we
1012 * need to maintain backward compatibility with many different
1013 * existing language translations and older sites.
1014 *
1015 * @uses $CFG
1016 */
02ebf404 1017function make_default_scale() {
02ebf404 1018
1019 global $CFG;
1020
1021 $defaultscale = NULL;
1022 $defaultscale->courseid = 0;
1023 $defaultscale->userid = 0;
d4419d55 1024 $defaultscale->name = get_string('separateandconnected');
1025 $defaultscale->scale = get_string('postrating1', 'forum').','.
1026 get_string('postrating2', 'forum').','.
1027 get_string('postrating3', 'forum');
02ebf404 1028 $defaultscale->timemodified = time();
1029
8f0cd6ef 1030 /// Read in the big description from the file. Note this is not
02ebf404 1031 /// HTML (despite the file extension) but Moodle format text.
d4419d55 1032 $parentlang = get_string('parentlang');
ee6e91d4 1033 if (is_readable($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
1034 $file = file($CFG->dataroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
1035 } else if (is_readable($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html')) {
d4419d55 1036 $file = file($CFG->dirroot .'/lang/'. $CFG->lang .'/help/forum/ratings.html');
ee6e91d4 1037 } else if ($parentlang and is_readable($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1038 $file = file($CFG->dataroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
d4419d55 1039 } else if ($parentlang and is_readable($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html')) {
1040 $file = file($CFG->dirroot .'/lang/'. $parentlang .'/help/forum/ratings.html');
ee6e91d4 1041 } else if (is_readable($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html')) {
1042 $file = file($CFG->dirroot .'/lang/en_utf8/help/forum/ratings.html');
02ebf404 1043 } else {
d4419d55 1044 $file = '';
02ebf404 1045 }
1046
d4419d55 1047 $defaultscale->description = addslashes(implode('', $file));
02ebf404 1048
d4419d55 1049 if ($defaultscale->id = insert_record('scale', $defaultscale)) {
1050 execute_sql('UPDATE '. $CFG->prefix .'forum SET scale = \''. $defaultscale->id .'\'', false);
02ebf404 1051 }
1052}
1053
fbc21ae8 1054
18a97fd8 1055/**
fbc21ae8 1056 * Returns a menu of all available scales from the site as well as the given course
1057 *
1058 * @uses $CFG
1059 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 1060 * @return object
fbc21ae8 1061 */
02ebf404 1062function get_scales_menu($courseid=0) {
02ebf404 1063
1064 global $CFG;
8f0cd6ef 1065
1066 $sql = "SELECT id, name FROM {$CFG->prefix}scale
1067 WHERE courseid = '0' or courseid = '$courseid'
02ebf404 1068 ORDER BY courseid ASC, name ASC";
1069
d4419d55 1070 if ($scales = get_records_sql_menu($sql)) {
02ebf404 1071 return $scales;
1072 }
1073
1074 make_default_scale();
1075
d4419d55 1076 return get_records_sql_menu($sql);
02ebf404 1077}
1078
5baa0ad6 1079
1080
1081/**
1082 * Given a set of timezone records, put them in the database, replacing what is there
1083 *
1084 * @uses $CFG
1085 * @param array $timezones An array of timezone records
1086 */
1087function update_timezone_records($timezones) {
1088/// Given a set of timezone records, put them in the database
1089
1090 global $CFG;
1091
1092/// Clear out all the old stuff
1093 execute_sql('TRUNCATE TABLE '.$CFG->prefix.'timezone', false);
1094
1095/// Insert all the new stuff
1096 foreach ($timezones as $timezone) {
1097 insert_record('timezone', $timezone);
1098 }
1099}
1100
1101
df28d6c5 1102/// MODULE FUNCTIONS /////////////////////////////////////////////////
1103
18a97fd8 1104/**
fbc21ae8 1105 * Just gets a raw list of all modules in a course
1106 *
1107 * @uses $CFG
1108 * @param int $courseid The id of the course as found in the 'course' table.
7290c7fa 1109 * @return object
fbc21ae8 1110 */
9fa49e22 1111function get_course_mods($courseid) {
9fa49e22 1112 global $CFG;
1113
3a11c548 1114 if (empty($courseid)) {
1115 return false; // avoid warnings
1116 }
1117
7acaa63d 1118 return get_records_sql("SELECT cm.*, m.name as modname
8f0cd6ef 1119 FROM {$CFG->prefix}modules m,
7acaa63d 1120 {$CFG->prefix}course_modules cm
8f0cd6ef 1121 WHERE cm.course = '$courseid'
9fa49e22 1122 AND cm.module = m.id ");
1123}
1124
fbc21ae8 1125
18a97fd8 1126/**
f9d5371b 1127 * Given an id of a course module, finds the coursemodule description
fbc21ae8 1128 *
f9d5371b 1129 * @param string $modulename name of module type, eg. resource, assignment,...
1130 * @param int $cmid course module id (id in course_modules table)
1131 * @param int $courseid optional course id for extra validation
1132 * @return object course module instance with instance and module name
1133 */
1134function get_coursemodule_from_id($modulename, $cmid, $courseid=0) {
1135
1136 global $CFG;
1137
1138 $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
1139
1140 return get_record_sql("SELECT cm.*, m.name, md.name as modname
1141 FROM {$CFG->prefix}course_modules cm,
1142 {$CFG->prefix}modules md,
1143 {$CFG->prefix}$modulename m
1144 WHERE $courseselect
1145 cm.id = '$cmid' AND
1146 cm.instance = m.id AND
1147 md.name = '$modulename' AND
1148 md.id = cm.module");
1149}
1150
1151/**
1152 * Given an instance number of a module, finds the coursemodule description
1153 *
1154 * @param string $modulename name of module type, eg. resource, assignment,...
1155 * @param int $instance module instance number (id in resource, assignment etc. table)
1156 * @param int $courseid optional course id for extra validation
1157 * @return object course module instance with instance and module name
fbc21ae8 1158 */
b63c0ee5 1159function get_coursemodule_from_instance($modulename, $instance, $courseid=0) {
df28d6c5 1160
1161 global $CFG;
f9d5371b 1162
b63c0ee5 1163 $courseselect = ($courseid) ? "cm.course = '$courseid' AND " : '';
df28d6c5 1164
f9d5371b 1165 return get_record_sql("SELECT cm.*, m.name, md.name as modname
8f0cd6ef 1166 FROM {$CFG->prefix}course_modules cm,
1167 {$CFG->prefix}modules md,
1168 {$CFG->prefix}$modulename m
b63c0ee5 1169 WHERE $courseselect
8f0cd6ef 1170 cm.instance = m.id AND
1171 md.name = '$modulename' AND
df28d6c5 1172 md.id = cm.module AND
1173 m.id = '$instance'");
1174
1175}
1176
185cfb09 1177/**
1178 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1179 *
1180 * Returns an array of all the active instances of a particular
1181 * module in given courses, sorted in the order they are defined
1182 * in the course. Returns false on any errors.
1183 *
1184 * @uses $CFG
1185 * @param string $modulename The name of the module to get instances for
613bbd7c 1186 * @param array $courses This depends on an accurate $course->modinfo
1187 * @return array of instances
185cfb09 1188 */
00e12c73 1189function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
185cfb09 1190 global $CFG;
1191 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1192 return array();
1193 }
1194 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode, cm.course
1195 FROM {$CFG->prefix}course_modules cm,
1196 {$CFG->prefix}course_sections cw,
1197 {$CFG->prefix}modules md,
1198 {$CFG->prefix}$modulename m
1199 WHERE cm.course IN (".implode(',',array_keys($courses)).") AND
1200 cm.instance = m.id AND
1201 cm.section = cw.id AND
1202 md.name = '$modulename' AND
1203 md.id = cm.module")) {
1204 return array();
1205 }
1206
1207 $outputarray = array();
1208
1209 foreach ($courses as $course) {
00e12c73 1210 if ($includeinvisible) {
1211 $invisible = -1;
1212 } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id), $userid)) {
1213 // Usually hide non-visible instances from students
185cfb09 1214 $invisible = -1;
1215 } else {
1216 $invisible = 0;
1217 }
fea43a7f 1218
1219 /// Casting $course->modinfo to string prevents one notice when the field is null
1220 if (!$modinfo = unserialize((string)$course->modinfo)) {
185cfb09 1221 continue;
1222 }
1223 foreach ($modinfo as $mod) {
1224 if ($mod->mod == $modulename and $mod->visible > $invisible) {
1225 $instance = $rawmods[$mod->cm];
1226 if (!empty($mod->extra)) {
1227 $instance->extra = $mod->extra;
1228 }
1229 $outputarray[] = $instance;
1230 }
1231 }
1232 }
1233
1234 return $outputarray;
1235
1236}
fbc21ae8 1237
18a97fd8 1238/**
fbc21ae8 1239 * Returns an array of all the active instances of a particular module in a given course, sorted in the order they are defined
1240 *
1241 * Returns an array of all the active instances of a particular
1242 * module in a given course, sorted in the order they are defined
1243 * in the course. Returns false on any errors.
1244 *
1245 * @uses $CFG
1246 * @param string $modulename The name of the module to get instances for
1247 * @param object(course) $course This depends on an accurate $course->modinfo
fbc21ae8 1248 */
00e12c73 1249function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
df28d6c5 1250
1251 global $CFG;
1252
3cc8b355 1253 if (empty($course->modinfo)) {
1254 return array();
1255 }
1256
fea43a7f 1257 if (!$modinfo = unserialize((string)$course->modinfo)) {
cccb016a 1258 return array();
1acfbce5 1259 }
1260
404afe6b 1261 if (!$rawmods = get_records_sql("SELECT cm.id as coursemodule, m.*,cw.section,cm.visible as visible,cm.groupmode
8f0cd6ef 1262 FROM {$CFG->prefix}course_modules cm,
1263 {$CFG->prefix}course_sections cw,
1264 {$CFG->prefix}modules md,
1265 {$CFG->prefix}$modulename m
1266 WHERE cm.course = '$course->id' AND
1267 cm.instance = m.id AND
8f0cd6ef 1268 cm.section = cw.id AND
1269 md.name = '$modulename' AND
cccb016a 1270 md.id = cm.module")) {
1271 return array();
1272 }
1273
00e12c73 1274 if ($includeinvisible) {
1275 $invisible = -1;
1276 } else if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id), $userid)) {
1277 // Usually hide non-visible instances from students
cccb016a 1278 $invisible = -1;
1279 } else {
1280 $invisible = 0;
1281 }
1282
78d4711e 1283 $outputarray = array();
1284
cccb016a 1285 foreach ($modinfo as $mod) {
1286 if ($mod->mod == $modulename and $mod->visible > $invisible) {
7f12f9cd 1287 $instance = $rawmods[$mod->cm];
1288 if (!empty($mod->extra)) {
1289 $instance->extra = $mod->extra;
1290 }
1291 $outputarray[] = $instance;
cccb016a 1292 }
1293 }
1294
1295 return $outputarray;
df28d6c5 1296
1297}
1298
9fa49e22 1299
18a97fd8 1300/**
fbc21ae8 1301 * Determine whether a module instance is visible within a course
1302 *
1303 * Given a valid module object with info about the id and course,
1304 * and the module's type (eg "forum") returns whether the object
1305 * is visible or not
1306 *
1307 * @uses $CFG
613bbd7c 1308 * @param $moduletype Name of the module eg 'forum'
1309 * @param $module Object which is the instance of the module
7290c7fa 1310 * @return bool
fbc21ae8 1311 */
580f2fbc 1312function instance_is_visible($moduletype, $module) {
580f2fbc 1313
1314 global $CFG;
1315
2b49ae96 1316 if (!empty($module->id)) {
1317 if ($records = get_records_sql("SELECT cm.instance, cm.visible
1318 FROM {$CFG->prefix}course_modules cm,
1319 {$CFG->prefix}modules m
1320 WHERE cm.course = '$module->course' AND
1321 cm.module = m.id AND
1322 m.name = '$moduletype' AND
1323 cm.instance = '$module->id'")) {
1324
1325 foreach ($records as $record) { // there should only be one - use the first one
1326 return $record->visible;
1327 }
580f2fbc 1328 }
1329 }
580f2fbc 1330 return true; // visible by default!
1331}
1332
a3fb1c45 1333
1334
1335
9fa49e22 1336/// LOG FUNCTIONS /////////////////////////////////////////////////////
1337
1338
18a97fd8 1339/**
fbc21ae8 1340 * Add an entry to the log table.
1341 *
1342 * Add an entry to the log table. These are "action" focussed rather
1343 * than web server hits, and provide a way to easily reconstruct what
1344 * any particular student has been doing.
1345 *
1346 * @uses $CFG
1347 * @uses $USER
1348 * @uses $db
1349 * @uses $REMOTE_ADDR
1350 * @uses SITEID
89dcb99d 1351 * @param int $courseid The course id
fbc21ae8 1352 * @param string $module The module name - e.g. forum, journal, resource, course, user etc
f7664880 1353 * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
fbc21ae8 1354 * @param string $url The file and parameters used to see the results of the action
1355 * @param string $info Additional description information
1356 * @param string $cm The course_module->id if there is one
1357 * @param string $user If log regards $user other than $USER
1358 */
d4419d55 1359function add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
e8395a09 1360 // Note that this function intentionally does not follow the normal Moodle DB access idioms.
1361 // This is for a good reason: it is the most frequently used DB update function,
1362 // so it has been optimised for speed.
fcaff7ff 1363 global $db, $CFG, $USER;
9fa49e22 1364
7a5b1fc5 1365 if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default
f78b3c34 1366 $cm = 0;
1367 }
1368
3d94772d 1369 if ($user) {
1370 $userid = $user;
1371 } else {
cb80265b 1372 if (!empty($USER->realuser)) { // Don't log
3d94772d 1373 return;
1374 }
d4419d55 1375 $userid = empty($USER->id) ? '0' : $USER->id;
9fa49e22 1376 }
1377
fcaff7ff 1378 $REMOTE_ADDR = getremoteaddr();
1379
9fa49e22 1380 $timenow = time();
1381 $info = addslashes($info);
10a760b9 1382 if (!empty($url)) { // could break doing html_entity_decode on an empty var.
1383 $url = html_entity_decode($url); // for php < 4.3.0 this is defined in moodlelib.php
1384 }
853df85e 1385
1386 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++; $PERF->logwrites++;};
1387
8b497bbc 1388 if ($CFG->type = 'oci8po') {
1389 if (empty($info)) {
1390 $info = ' ';
1391 }
1392 }
1393
d4419d55 1394 $result = $db->Execute('INSERT INTO '. $CFG->prefix .'log (time, userid, course, ip, module, cmid, action, url, info)
1395 VALUES (' . "'$timenow', '$userid', '$courseid', '$REMOTE_ADDR', '$module', '$cm', '$action', '$url', '$info')");
ebc3bd2b 1396
ea82d6b6 1397 if (!$result and debugging()) {
d4419d55 1398 echo '<p>Error: Could not insert a new entry to the Moodle log</p>'; // Don't throw an error
8f0cd6ef 1399 }
cb80265b 1400
1401/// Store lastaccess times for the current user
1402
1403 if (!empty($USER->id) && ($userid == $USER->id) ) {
1404 $db->Execute('UPDATE '. $CFG->prefix .'user
1405 SET lastip=\''. $REMOTE_ADDR .'\', lastaccess=\''. $timenow .'\'
1406 WHERE id = \''. $userid .'\' ');
1407 if ($courseid != SITEID && !empty($courseid)) {
853df85e 1408 if (defined('MDL_PERFDB')) { global $PERF ; $PERF->dbqueries++;};
1c45e42e 1409
cb80265b 1410 if ($record = get_record('user_lastaccess', 'userid', $userid, 'courseid', $courseid)) {
1411 $record->timeaccess = $timenow;
1412 return update_record('user_lastaccess', $record);
1413 } else {
ae9e4c06 1414 $record = new object;
1415 $record->userid = $userid;
1416 $record->courseid = $courseid;
1417 $record->timeaccess = $timenow;
1418 return insert_record('user_lastaccess', $record);
114176a2 1419 }
3d94772d 1420 }
8f0cd6ef 1421 }
9fa49e22 1422}
1423
1424
18a97fd8 1425/**
fbc21ae8 1426 * Select all log records based on SQL criteria
1427 *
1428 * @uses $CFG
1429 * @param string $select SQL select criteria
1430 * @param string $order SQL order by clause to sort the records returned
1431 * @param string $limitfrom ?
1432 * @param int $limitnum ?
1433 * @param int $totalcount Passed in by reference.
7290c7fa 1434 * @return object
fbc21ae8 1435 * @todo Finish documenting this function
1436 */
d4419d55 1437function get_logs($select, $order='l.time DESC', $limitfrom='', $limitnum='', &$totalcount) {
9fa49e22 1438 global $CFG;
1439
519d369f 1440 if ($order) {
d4419d55 1441 $order = 'ORDER BY '. $order;
519d369f 1442 }
1443
fbc21ae8 1444 $selectsql = $CFG->prefix .'log l LEFT JOIN '. $CFG->prefix .'user u ON l.userid = u.id '. ((strlen($select) > 0) ? 'WHERE '. $select : '');
a2ddd957 1445 $countsql = $CFG->prefix.'log l '.((strlen($select) > 0) ? ' WHERE '. $select : '');
1446
1447 $totalcount = count_records_sql("SELECT COUNT(*) FROM $countsql");
519d369f 1448
d4419d55 1449 return get_records_sql('SELECT l.*, u.firstname, u.lastname, u.picture
93a89227 1450 FROM '. $selectsql .' '. $order, $limitfrom, $limitnum) ;
9fa49e22 1451}
1452
519d369f 1453
18a97fd8 1454/**
fbc21ae8 1455 * Select all log records for a given course and user
1456 *
1457 * @uses $CFG
2f87145b 1458 * @uses DAYSECS
fbc21ae8 1459 * @param int $userid The id of the user as found in the 'user' table.
1460 * @param int $courseid The id of the course as found in the 'course' table.
1461 * @param string $coursestart ?
1462 * @todo Finish documenting this function
1463 */
9fa49e22 1464function get_logs_usercourse($userid, $courseid, $coursestart) {
1465 global $CFG;
1466
da0c90c3 1467 if ($courseid) {
d4419d55 1468 $courseselect = ' AND course = \''. $courseid .'\' ';
2700d113 1469 } else {
1470 $courseselect = '';
da0c90c3 1471 }
1472
1604a0fc 1473 return get_records_sql("SELECT floor((time - $coursestart)/". DAYSECS .") as day, count(*) as num
8f0cd6ef 1474 FROM {$CFG->prefix}log
1475 WHERE userid = '$userid'
1604a0fc 1476 AND time > '$coursestart' $courseselect
9fa49e22 1477 GROUP BY day ");
1478}
1479
18a97fd8 1480/**
fbc21ae8 1481 * Select all log records for a given course, user, and day
1482 *
1483 * @uses $CFG
2f87145b 1484 * @uses HOURSECS
fbc21ae8 1485 * @param int $userid The id of the user as found in the 'user' table.
1486 * @param int $courseid The id of the course as found in the 'course' table.
1487 * @param string $daystart ?
7290c7fa 1488 * @return object
fbc21ae8 1489 * @todo Finish documenting this function
1490 */
9fa49e22 1491function get_logs_userday($userid, $courseid, $daystart) {
1492 global $CFG;
1493
7e4a6488 1494 if ($courseid) {
d4419d55 1495 $courseselect = ' AND course = \''. $courseid .'\' ';
2700d113 1496 } else {
1497 $courseselect = '';
7e4a6488 1498 }
1499
1604a0fc 1500 return get_records_sql("SELECT floor((time - $daystart)/". HOURSECS .") as hour, count(*) as num
9fa49e22 1501 FROM {$CFG->prefix}log
8f0cd6ef 1502 WHERE userid = '$userid'
1604a0fc 1503 AND time > '$daystart' $courseselect
9fa49e22 1504 GROUP BY hour ");
1505}
1506
b4bac9b6 1507/**
1508 * Returns an object with counts of failed login attempts
1509 *
8f0cd6ef 1510 * Returns information about failed login attempts. If the current user is
1511 * an admin, then two numbers are returned: the number of attempts and the
b4bac9b6 1512 * number of accounts. For non-admins, only the attempts on the given user
1513 * are shown.
1514 *
fbc21ae8 1515 * @param string $mode Either 'admin', 'teacher' or 'everybody'
1516 * @param string $username The username we are searching for
1517 * @param string $lastlogin The date from which we are searching
1518 * @return int
b4bac9b6 1519 */
b4bac9b6 1520function count_login_failures($mode, $username, $lastlogin) {
1521
d4419d55 1522 $select = 'module=\'login\' AND action=\'error\' AND time > '. $lastlogin;
b4bac9b6 1523
51792df0 1524 if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM, SITEID))) { // Return information about all accounts
b4bac9b6 1525 if ($count->attempts = count_records_select('log', $select)) {
1526 $count->accounts = count_records_select('log', $select, 'COUNT(DISTINCT info)');
1527 return $count;
1528 }
9407d456 1529 } else if ($mode == 'everybody' or ($mode == 'teacher' and isteacherinanycourse())) {
d4419d55 1530 if ($count->attempts = count_records_select('log', $select .' AND info = \''. $username .'\'')) {
b4bac9b6 1531 return $count;
1532 }
1533 }
1534 return NULL;
1535}
1536
1537
a3fb1c45 1538/// GENERAL HELPFUL THINGS ///////////////////////////////////
1539
18a97fd8 1540/**
fbc21ae8 1541 * Dump a given object's information in a PRE block.
1542 *
1543 * Mostly just used for debugging.
1544 *
1545 * @param mixed $object The data to be printed
fbc21ae8 1546 */
a3fb1c45 1547function print_object($object) {
1aa1044f 1548 echo '<pre>'.htmlspecialchars(print_r($object,true)).'</pre>';
a3fb1c45 1549}
1550
0986271b 1551function course_parent_visible($course = null) {
fa145ae1 1552 global $CFG;
1553
418b4e5a 1554 if (empty($course)) {
1555 return true;
1556 }
1557 if (!empty($CFG->allowvisiblecoursesinhiddencategories)) {
1558 return true;
1559 }
0986271b 1560 return category_parent_visible($course->category);
1561}
1562
1563function category_parent_visible($parent = 0) {
824f1c40 1564
1565 static $visible;
1566
0986271b 1567 if (!$parent) {
1568 return true;
1569 }
824f1c40 1570
1571 if (empty($visible)) {
1572 $visible = array(); // initialize
1573 }
1574
1575 if (array_key_exists($parent,$visible)) {
1576 return $visible[$parent];
1577 }
1578
0986271b 1579 $category = get_record('course_categories', 'id', $parent);
1580 $list = explode('/', preg_replace('/^\/(.*)$/', '$1', $category->path));
1581 $list[] = $parent;
1582 $parents = get_records_list('course_categories', 'id', implode(',', $list), 'depth DESC');
824f1c40 1583 $v = true;
1584 foreach ($parents as $p) {
1585 if (!$p->visible) {
1586 $v = false;
0986271b 1587 }
1588 }
824f1c40 1589 $visible[$parent] = $v; // now cache it
1590 return $v;
0986271b 1591}
1592
62d4e774 1593/**
1594 * This function is the official hook inside XMLDB stuff to delegate its debug to one
1595 * external function.
1596 *
1597 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1598 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1599 *
1600 * @param $message string contains the error message
1601 * @param $object object XMLDB object that fired the debug
1602 */
1603function xmldb_debug($message, $object) {
1604
1605 error_log($message);
1606}
1607
9d5b689c 1608// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
03517306 1609?>