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