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