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