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