on-demand release 2.3dev
[moodle.git] / lib / completionlib.php
CommitLineData
4e781c7b 1<?php
117bd748
PS
2// This file is part of Moodle - http://moodle.org/
3//
09639ded 4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
117bd748 13//
09639ded 14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
836375ec
SH
18 * Contains classes, functions and constants used during the tracking
19 * of activity completion for users.
09639ded 20 *
21 * Completion top-level options (admin setting enablecompletion)
117bd748 22 *
836375ec
SH
23 * @package core_completion
24 * @category completion
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
09639ded 27 */
4e781c7b 28
78bfb562
PS
29defined('MOODLE_INTERNAL') || die();
30
836375ec
SH
31/**
32 * Include the required completion libraries
33 */
78bfb562
PS
34require_once $CFG->libdir.'/completion/completion_aggregation.php';
35require_once $CFG->libdir.'/completion/completion_criteria.php';
36require_once $CFG->libdir.'/completion/completion_completion.php';
37require_once $CFG->libdir.'/completion/completion_criteria_completion.php';
38
39
836375ec
SH
40/**
41 * The completion system is enabled in this site/course
42 */
0d5d12bd 43define('COMPLETION_ENABLED', 1);
836375ec
SH
44/**
45 * The completion system is not enabled in this site/course
46 */
0d5d12bd 47define('COMPLETION_DISABLED', 0);
4e781c7b 48
836375ec
SH
49/**
50 * Completion tracking is disabled for this activity
51 * This is a completion tracking option per-activity (course_modules/completion)
52 */
0d5d12bd 53define('COMPLETION_TRACKING_NONE', 0);
836375ec
SH
54
55/**
56 * Manual completion tracking (user ticks box) is enabled for this activity
57 * This is a completion tracking option per-activity (course_modules/completion)
58 */
0d5d12bd 59define('COMPLETION_TRACKING_MANUAL', 1);
836375ec
SH
60/**
61 * Automatic completion tracking (system ticks box) is enabled for this activity
62 * This is a completion tracking option per-activity (course_modules/completion)
63 */
0d5d12bd 64define('COMPLETION_TRACKING_AUTOMATIC', 2);
4e781c7b 65
836375ec
SH
66/**
67 * The user has not completed this activity.
68 * This is a completion state value (course_modules_completion/completionstate)
69 */
0d5d12bd 70define('COMPLETION_INCOMPLETE', 0);
836375ec
SH
71/**
72 * The user has completed this activity. It is not specified whether they have
73 * passed or failed it.
74 * This is a completion state value (course_modules_completion/completionstate)
75 */
0d5d12bd 76define('COMPLETION_COMPLETE', 1);
836375ec
SH
77/**
78 * The user has completed this activity with a grade above the pass mark.
79 * This is a completion state value (course_modules_completion/completionstate)
80 */
0d5d12bd 81define('COMPLETION_COMPLETE_PASS', 2);
836375ec
SH
82/**
83 * The user has completed this activity but their grade is less than the pass mark
84 * This is a completion state value (course_modules_completion/completionstate)
85 */
0d5d12bd 86define('COMPLETION_COMPLETE_FAIL', 3);
4e781c7b 87
836375ec
SH
88/**
89 * The effect of this change to completion status is unknown.
90 * A completion effect changes (used only in update_state)
91 */
0d5d12bd 92define('COMPLETION_UNKNOWN', -1);
836375ec
SH
93/**
94 * The user's grade has changed, so their new state might be
95 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
96 * A completion effect changes (used only in update_state)
97 */
0d5d12bd 98define('COMPLETION_GRADECHANGE', -2);
4e781c7b 99
836375ec 100/**
95dd54ee 101 * User must view this activity.
836375ec
SH
102 * Whether view is required to create an activity (course_modules/completionview)
103 */
0d5d12bd 104define('COMPLETION_VIEW_REQUIRED', 1);
836375ec
SH
105/**
106 * User does not need to view this activity
107 * Whether view is required to create an activity (course_modules/completionview)
108 */
0d5d12bd 109define('COMPLETION_VIEW_NOT_REQUIRED', 0);
4e781c7b 110
836375ec
SH
111/**
112 * User has viewed this activity.
113 * Completion viewed state (course_modules_completion/viewed)
114 */
0d5d12bd 115define('COMPLETION_VIEWED', 1);
836375ec
SH
116/**
117 * User has not viewed this activity.
118 * Completion viewed state (course_modules_completion/viewed)
119 */
0d5d12bd 120define('COMPLETION_NOT_VIEWED', 0);
4e781c7b 121
836375ec
SH
122/**
123 * Cache expiry time in seconds (10 minutes)
124 * Completion cacheing
125 */
0d5d12bd 126define('COMPLETION_CACHE_EXPIRY', 10*60);
4e781c7b 127
836375ec
SH
128/**
129 * Completion details should be ORed together and you should return false if
130 * none apply.
131 */
0d5d12bd 132define('COMPLETION_OR', false);
836375ec
SH
133/**
134 * Completion details should be ANDed together and you should return true if
135 * none apply
136 */
0d5d12bd 137define('COMPLETION_AND', true);
4e781c7b 138
836375ec
SH
139/**
140 * Course completion criteria aggregation method.
141 */
142define('COMPLETION_AGGREGATION_ALL', 1);
143/**
144 * Course completion criteria aggregation method.
145 */
146define('COMPLETION_AGGREGATION_ANY', 2);
2be4d090
MD
147
148
4e781c7b 149/**
150 * Class represents completion information for a course.
09639ded 151 *
152 * Does not contain any data, so you can safely construct it multiple times
153 * without causing any problems.
154 *
836375ec
SH
155 * @package core
156 * @category completion
157 * @copyright 2008 Sam Marshall
09639ded 158 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4e781c7b 159 */
160class completion_info {
836375ec 161
95dd54ee 162 /* @var stdClass Course object passed during construction */
4e781c7b 163 private $course;
0d5d12bd 164
95dd54ee 165 /* @var int Course id */
2be4d090
MD
166 public $course_id;
167
f55ff38a 168 /* @var array Completion criteria {@link completion_info::get_criteria()} */
2be4d090
MD
169 private $criteria;
170
171 /**
172 * Return array of aggregation methods
836375ec 173 * @return array
2be4d090
MD
174 */
175 public static function get_aggregation_methods() {
176 return array(
836375ec
SH
177 COMPLETION_AGGREGATION_ALL => get_string('all'),
178 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
2be4d090
MD
179 );
180 }
181
4e781c7b 182 /**
183 * Constructs with course details.
184 *
836375ec
SH
185 * When instantiating a new completion info object you must provide a course
186 * object with at least id, and enablecompletion properties.
187 *
188 * @param stdClass $course Moodle course object.
4e781c7b 189 */
49f6e5f4 190 public function __construct($course) {
0d5d12bd 191 $this->course = $course;
2be4d090 192 $this->course_id = $course->id;
4e781c7b 193 }
194
195 /**
09639ded 196 * Determines whether completion is enabled across entire site.
117bd748 197 *
836375ec 198 * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
4e781c7b 199 * COMPLETION_DISABLED (false) if it's complete
200 */
201 public static function is_enabled_for_site() {
202 global $CFG;
1caea91e 203 return !empty($CFG->enablecompletion);
4e781c7b 204 }
0d5d12bd 205
4e781c7b 206 /**
207 * Checks whether completion is enabled in a particular course and possibly
208 * activity.
209 *
836375ec 210 * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
4e781c7b 211 * completion enable state.
09639ded 212 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
4e781c7b 213 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
214 * for a course-module.
215 */
836375ec 216 public function is_enabled($cm = null) {
7075e37e 217 global $CFG, $DB;
d7d87535 218
219 // First check global completion
250c0533 220 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
4e781c7b 221 return COMPLETION_DISABLED;
222 }
0d5d12bd 223
7075e37e
AB
224 // Load data if we do not have enough
225 if (!isset($this->course->enablecompletion)) {
226 $this->course->enablecompletion = $DB->get_field('course', 'enablecompletion', array('id' => $this->course->id));
227 }
228
4e781c7b 229 // Check course completion
0d5d12bd 230 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
4e781c7b 231 return COMPLETION_DISABLED;
232 }
0d5d12bd 233
4e781c7b 234 // If there was no $cm and we got this far, then it's enabled
0d5d12bd 235 if (!$cm) {
4e781c7b 236 return COMPLETION_ENABLED;
237 }
0d5d12bd 238
4e781c7b 239 // Return course-module completion value
240 return $cm->completion;
241 }
0d5d12bd 242
2af26b12 243 /**
244 * Displays the 'Your progress' help icon, if completion tracking is enabled.
245 * Just prints the result of display_help_icon().
836375ec
SH
246 *
247 * @deprecated since Moodle 2.0 - Use display_help_icon instead.
2af26b12 248 */
249 public function print_help_icon() {
250 print $this->display_help_icon();
251 }
252
e3568fde 253 /**
563e97b8 254 * Returns the 'Your progress' help icon, if completion tracking is enabled.
836375ec 255 *
563e97b8 256 * @return string HTML code for help icon, or blank if not needed
e3568fde 257 */
563e97b8 258 public function display_help_icon() {
aa9a6867 259 global $PAGE, $OUTPUT;
563e97b8 260 $result = '';
e3568fde 261 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
563e97b8 262 $result .= '<span id = "completionprogressid" class="completionprogress">'.get_string('yourprogress','completion').' ';
263 $result .= $OUTPUT->help_icon('completionicons', 'completion');
264 $result .= '</span>';
e3568fde 265 }
563e97b8 266 return $result;
e3568fde 267 }
2be4d090
MD
268
269 /**
270 * Get a course completion for a user
836375ec
SH
271 *
272 * @param int $user_id User id
273 * @param int $criteriatype Specific criteria type to return
95dd54ee 274 * @return bool|completion_criteria_completion returns false on fail
2be4d090
MD
275 */
276 public function get_completion($user_id, $criteriatype) {
277 $completions = $this->get_completions($user_id, $criteriatype);
278
279 if (empty($completions)) {
280 return false;
281 } elseif (count($completions) > 1) {
282 print_error('multipleselfcompletioncriteria', 'completion');
283 }
284
285 return $completions[0];
286 }
287
288 /**
289 * Get all course criteria's completion objects for a user
836375ec
SH
290 *
291 * @param int $user_id User id
292 * @param int $criteriatype Specific criteria type to return (optional)
293 * @return array
2be4d090
MD
294 */
295 public function get_completions($user_id, $criteriatype = null) {
296 $criterion = $this->get_criteria($criteriatype);
297
298 $completions = array();
299
300 foreach ($criterion as $criteria) {
301 $params = array(
302 'course' => $this->course_id,
303 'userid' => $user_id,
304 'criteriaid' => $criteria->id
305 );
306
307 $completion = new completion_criteria_completion($params);
308 $completion->attach_criteria($criteria);
309
310 $completions[] = $completion;
311 }
312
313 return $completions;
314 }
315
316 /**
317 * Get completion object for a user and a criteria
836375ec
SH
318 *
319 * @param int $user_id User id
320 * @param completion_criteria $criteria Criteria object
321 * @return completion_criteria_completion
2be4d090
MD
322 */
323 public function get_user_completion($user_id, $criteria) {
324 $params = array(
dbfcf440
AB
325 'course' => $this->course_id,
326 'userid' => $user_id,
2be4d090 327 'criteriaid' => $criteria->id,
2be4d090
MD
328 );
329
330 $completion = new completion_criteria_completion($params);
331 return $completion;
332 }
333
334 /**
335 * Check if course has completion criteria set
336 *
836375ec 337 * @return bool Returns true if there are criteria
2be4d090
MD
338 */
339 public function has_criteria() {
340 $criteria = $this->get_criteria();
341
342 return (bool) count($criteria);
343 }
344
2be4d090
MD
345 /**
346 * Get course completion criteria
836375ec
SH
347 *
348 * @param int $criteriatype Specific criteria type to return (optional)
2be4d090
MD
349 */
350 public function get_criteria($criteriatype = null) {
351
352 // Fill cache if empty
353 if (!is_array($this->criteria)) {
354 global $DB;
355
356 $params = array(
357 'course' => $this->course->id
358 );
359
360 // Load criteria from database
361 $records = (array)$DB->get_records('course_completion_criteria', $params);
362
363 // Build array of criteria objects
364 $this->criteria = array();
365 foreach ($records as $record) {
dbfcf440 366 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
2be4d090
MD
367 }
368 }
369
370 // If after all criteria
371 if ($criteriatype === null) {
372 return $this->criteria;
373 }
374
375 // If we are only after a specific criteria type
376 $criteria = array();
377 foreach ($this->criteria as $criterion) {
378
379 if ($criterion->criteriatype != $criteriatype) {
380 continue;
381 }
382
383 $criteria[$criterion->id] = $criterion;
384 }
385
386 return $criteria;
387 }
388
389 /**
390 * Get aggregation method
836375ec
SH
391 *
392 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
393 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
2be4d090
MD
394 */
395 public function get_aggregation_method($criteriatype = null) {
396 $params = array(
397 'course' => $this->course_id,
398 'criteriatype' => $criteriatype
399 );
400
401 $aggregation = new completion_aggregation($params);
402
403 if (!$aggregation->id) {
404 $aggregation->method = COMPLETION_AGGREGATION_ALL;
405 }
406
407 return $aggregation->method;
408 }
409
410 /**
411 * Get incomplete course completion criteria
836375ec
SH
412 *
413 * @return array
2be4d090
MD
414 */
415 public function get_incomplete_criteria() {
416 $incomplete = array();
417
418 foreach ($this->get_criteria() as $criteria) {
419 if (!$criteria->is_complete()) {
420 $incomplete[] = $criteria;
421 }
422 }
423
424 return $incomplete;
425 }
426
427 /**
428 * Clear old course completion criteria
429 */
430 public function clear_criteria() {
431 global $DB;
432 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id));
433 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
434
435 $this->delete_course_completion_data();
436 }
437
438 /**
439 * Has the supplied user completed this course
836375ec
SH
440 *
441 * @param int $user_id User's id
442 * @return boolean
2be4d090
MD
443 */
444 public function is_course_complete($user_id) {
445 $params = array(
446 'userid' => $user_id,
447 'course' => $this->course_id
448 );
449
450 $ccompletion = new completion_completion($params);
451 return $ccompletion->is_complete();
452 }
453
4e781c7b 454 /**
455 * Updates (if necessary) the completion state of activity $cm for the given
456 * user.
09639ded 457 *
4e781c7b 458 * For manual completion, this function is called when completion is toggled
459 * with $possibleresult set to the target state.
09639ded 460 *
4e781c7b 461 * For automatic completion, this function should be called every time a module
462 * does something which might influence a user's completion state. For example,
463 * if a forum provides options for marking itself 'completed' once a user makes
464 * N posts, this function should be called every time a user makes a new post.
465 * [After the post has been saved to the database]. When calling, you do not
466 * need to pass in the new completion state. Instead this function carries out
467 * completion calculation by checking grades and viewed state itself, and
468 * calling the involved module via modulename_get_completion_state() to check
469 * module-specific conditions.
470 *
7142a755 471 * @param stdClass|cm_info $cm Course-module
4e781c7b 472 * @param int $possibleresult Expected completion result. If the event that
473 * has just occurred (e.g. add post) can only result in making the activity
474 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
475 * has just occurred (e.g. delete post) can only result in making the activity
476 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
477 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
478 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
479 * processing early if the user's completion state already matches the expected
480 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
481 * must be used; these directly set the specified state.
482 * @param int $userid User ID to be updated. Default 0 = current user
09639ded 483 * @return void
4e781c7b 484 */
0d5d12bd 485 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
486 global $USER, $SESSION;
d7d87535 487
0d5d12bd 488 // Do nothing if completion is not enabled for that activity
489 if (!$this->is_enabled($cm)) {
4e781c7b 490 return;
491 }
0d5d12bd 492
4e781c7b 493 // Get current value of completion state and do nothing if it's same as
494 // the possible result of this change. If the change is to COMPLETE and the
495 // current value is one of the COMPLETE_xx subtypes, ignore that as well
0d5d12bd 496 $current = $this->get_data($cm, false, $userid);
497 if ($possibleresult == $current->completionstate ||
498 ($possibleresult == COMPLETION_COMPLETE &&
499 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
500 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
4e781c7b 501 return;
502 }
0d5d12bd 503
504 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
4e781c7b 505 // For manual tracking we set the result directly
506 switch($possibleresult) {
507 case COMPLETION_COMPLETE:
508 case COMPLETION_INCOMPLETE:
0d5d12bd 509 $newstate = $possibleresult;
4e781c7b 510 break;
511 default:
512 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
513 }
d7d87535 514
4e781c7b 515 } else {
516 // Automatic tracking; get new state
0d5d12bd 517 $newstate = $this->internal_get_state($cm, $userid, $current);
4e781c7b 518 }
0d5d12bd 519
4e781c7b 520 // If changed, update
0d5d12bd 521 if ($newstate != $current->completionstate) {
522 $current->completionstate = $newstate;
523 $current->timemodified = time();
524 $this->internal_set_data($cm, $current);
4e781c7b 525 }
526 }
0d5d12bd 527
4e781c7b 528 /**
529 * Calculates the completion state for an activity and user.
4e781c7b 530 *
09639ded 531 * Internal function. Not private, so we can unit-test it.
95dd54ee 532 *
836375ec 533 * @param stdClass|cm_info $cm Activity
4e781c7b 534 * @param int $userid ID of user
836375ec 535 * @param stdClass $current Previous completion information from database
09639ded 536 * @return mixed
4e781c7b 537 */
836375ec 538 public function internal_get_state($cm, $userid, $current) {
7a7dbd77 539 global $USER, $DB, $CFG;
d7d87535 540
541 // Get user ID
0d5d12bd 542 if (!$userid) {
543 $userid = $USER->id;
4e781c7b 544 }
0d5d12bd 545
4e781c7b 546 // Check viewed
0d5d12bd 547 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
548 $current->viewed == COMPLETION_NOT_VIEWED) {
549
4e781c7b 550 return COMPLETION_INCOMPLETE;
551 }
0d5d12bd 552
4e781c7b 553 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
0d5d12bd 554 if (!isset($cm->modname)) {
555 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
4e781c7b 556 }
0d5d12bd 557
558 $newstate = COMPLETION_COMPLETE;
559
4e781c7b 560 // Check grade
0d5d12bd 561 if (!is_null($cm->completiongradeitemnumber)) {
7a7dbd77 562 require_once($CFG->libdir.'/gradelib.php');
0d5d12bd 563 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
564 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
4e781c7b 565 'itemnumber'=>$cm->completiongradeitemnumber));
0d5d12bd 566 if ($item) {
4e781c7b 567 // Fetch 'grades' (will be one or none)
0d5d12bd 568 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
569 if (empty($grades)) {
4e781c7b 570 // No grade for user
571 return COMPLETION_INCOMPLETE;
572 }
0d5d12bd 573 if (count($grades) > 1) {
4e781c7b 574 $this->internal_systemerror("Unexpected result: multiple grades for
575 item '{$item->id}', user '{$userid}'");
576 }
4218d813 577 $newstate = self::internal_get_grade_state($item, reset($grades));
0d5d12bd 578 if ($newstate == COMPLETION_INCOMPLETE) {
4e781c7b 579 return COMPLETION_INCOMPLETE;
580 }
d7d87535 581
4e781c7b 582 } else {
583 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
584 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
585 }
586 }
0d5d12bd 587
588 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
589 $function = $cm->modname.'_get_completion_state';
590 if (!function_exists($function)) {
4e781c7b 591 $this->internal_systemerror("Module {$cm->modname} claims to support
592 FEATURE_COMPLETION_HAS_RULES but does not have required
593 {$cm->modname}_get_completion_state function");
594 }
0d5d12bd 595 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
4e781c7b 596 return COMPLETION_INCOMPLETE;
597 }
598 }
0d5d12bd 599
4e781c7b 600 return $newstate;
0d5d12bd 601
4e781c7b 602 }
0d5d12bd 603
4e781c7b 604 /**
605 * Marks a module as viewed.
09639ded 606 *
4e781c7b 607 * Should be called whenever a module is 'viewed' (it is up to the module how to
608 * determine that). Has no effect if viewing is not set as a completion condition.
609 *
6553cda7 610 * Note that this function must be called before you print the page header because
611 * it is possible that the navigation block may depend on it. If you call it after
612 * printing the header, it shows a developer debug warning.
836375ec
SH
613 *
614 * @param stdClass|cm_info $cm Activity
4e781c7b 615 * @param int $userid User ID or 0 (default) for current user
09639ded 616 * @return void
4e781c7b 617 */
0d5d12bd 618 public function set_module_viewed($cm, $userid=0) {
1cec45f1 619 global $PAGE, $UNITTEST;
620 if ($PAGE->headerprinted && empty($UNITTEST->running)) {
6553cda7 621 debugging('set_module_viewed must be called before header is printed',
622 DEBUG_DEVELOPER);
623 }
4e781c7b 624 // Don't do anything if view condition is not turned on
0d5d12bd 625 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
4e781c7b 626 return;
627 }
628 // Get current completion state
0d5d12bd 629 $data = $this->get_data($cm, $userid);
4e781c7b 630 // If we already viewed it, don't do anything
0d5d12bd 631 if ($data->viewed == COMPLETION_VIEWED) {
4e781c7b 632 return;
633 }
634 // OK, change state, save it, and update completion
0d5d12bd 635 $data->viewed = COMPLETION_VIEWED;
636 $this->internal_set_data($cm, $data);
637 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
4e781c7b 638 }
0d5d12bd 639
4e781c7b 640 /**
641 * Determines how much completion data exists for an activity. This is used when
642 * deciding whether completion information should be 'locked' in the module
643 * editing form.
644 *
836375ec 645 * @param cm_info $cm Activity
4e781c7b 646 * @return int The number of users who have completion data stored for this
0d5d12bd 647 * activity, 0 if none
4e781c7b 648 */
649 public function count_user_data($cm) {
2be4d090 650 global $DB;
0d5d12bd 651
4e781c7b 652 return $DB->get_field_sql("
653 SELECT
654 COUNT(1)
655 FROM
49f6e5f4 656 {course_modules_completion}
4e781c7b 657 WHERE
0d5d12bd 658 coursemoduleid=? AND completionstate<>0", array($cm->id));
4e781c7b 659 }
0d5d12bd 660
2be4d090
MD
661 /**
662 * Determines how much course completion data exists for a course. This is used when
663 * deciding whether completion information should be 'locked' in the completion
664 * settings form and activity completion settings.
665 *
836375ec 666 * @param int $user_id Optionally only get course completion data for a single user
2be4d090 667 * @return int The number of users who have completion data stored for this
836375ec 668 * course, 0 if none
2be4d090
MD
669 */
670 public function count_course_user_data($user_id = null) {
671 global $DB;
672
673 $sql = '
674 SELECT
675 COUNT(1)
676 FROM
677 {course_completion_crit_compl}
678 WHERE
679 course = ?
680 ';
681
682 $params = array($this->course_id);
683
684 // Limit data to a single user if an ID is supplied
685 if ($user_id) {
686 $sql .= ' AND userid = ?';
687 $params[] = $user_id;
688 }
689
690 return $DB->get_field_sql($sql, $params);
691 }
692
693 /**
694 * Check if this course's completion criteria should be locked
695 *
836375ec 696 * @return boolean
2be4d090
MD
697 */
698 public function is_course_locked() {
699 return (bool) $this->count_course_user_data();
700 }
701
702 /**
703 * Deletes all course completion completion data.
704 *
705 * Intended to be used when unlocking completion criteria settings.
2be4d090
MD
706 */
707 public function delete_course_completion_data() {
708 global $DB;
709
710 $DB->delete_records('course_completions', array('course' => $this->course_id));
711 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
712 }
713
4e781c7b 714 /**
0d5d12bd 715 * Deletes completion state related to an activity for all users.
117bd748 716 *
4e781c7b 717 * Intended for use only when the activity itself is deleted.
718 *
836375ec 719 * @param stdClass|cm_info $cm Activity
4e781c7b 720 */
0d5d12bd 721 public function delete_all_state($cm) {
722 global $SESSION, $DB;
723
4e781c7b 724 // Delete from database
0d5d12bd 725 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
726
4e781c7b 727 // Erase cache data for current user if applicable
0d5d12bd 728 if (isset($SESSION->completioncache) &&
729 array_key_exists($cm->course, $SESSION->completioncache) &&
730 array_key_exists($cm->id, $SESSION->completioncache[$cm->course])) {
731
4e781c7b 732 unset($SESSION->completioncache[$cm->course][$cm->id]);
733 }
2be4d090
MD
734
735 // Check if there is an associated course completion criteria
736 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
737 $acriteria = false;
738 foreach ($criteria as $criterion) {
739 if ($criterion->moduleinstance == $cm->id) {
740 $acriteria = $criterion;
741 break;
836375ec 742 }
2be4d090
MD
743 }
744
745 if ($acriteria) {
746 // Delete all criteria completions relating to this activity
747 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
748 $DB->delete_records('course_completions', array('course' => $this->course_id));
749 }
4e781c7b 750 }
0d5d12bd 751
4e781c7b 752 /**
753 * Recalculates completion state related to an activity for all users.
117bd748 754 *
4e781c7b 755 * Intended for use if completion conditions change. (This should be avoided
756 * as it may cause some things to become incomplete when they were previously
757 * complete, with the effect - for example - of hiding a later activity that
758 * was previously available.)
117bd748 759 *
0d5d12bd 760 * Resetting state of manual tickbox has same result as deleting state for
81f64ed3 761 * it.
09639ded 762 *
836375ec 763 * @param stcClass|cm_info $cm Activity
4e781c7b 764 */
765 public function reset_all_state($cm) {
d7d87535 766 global $DB;
767
0d5d12bd 768 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
81f64ed3 769 $this->delete_all_state($cm);
770 return;
771 }
4e781c7b 772 // Get current list of users with completion state
0d5d12bd 773 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
774 $keepusers = array();
775 foreach ($rs as $rec) {
776 $keepusers[] = $rec->userid;
4e781c7b 777 }
778 $rs->close();
0d5d12bd 779
4e781c7b 780 // Delete all existing state [also clears session cache for current user]
781 $this->delete_all_state($cm);
0d5d12bd 782
783 // Merge this with list of planned users (according to roles)
24a3b341 784 $trackedusers = $this->get_tracked_users();
0d5d12bd 785 foreach ($trackedusers as $trackeduser) {
786 $keepusers[] = $trackeduser->id;
787 }
788 $keepusers = array_unique($keepusers);
789
4e781c7b 790 // Recalculate state for each kept user
0d5d12bd 791 foreach ($keepusers as $keepuser) {
792 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
4e781c7b 793 }
794 }
0d5d12bd 795
4e781c7b 796 /**
797 * Obtains completion data for a particular activity and user (from the
798 * session cache if available, or by SQL query)
799 *
836375ec 800 * @param stcClass|cm_info $cm Activity; only required field is ->id
4e781c7b 801 * @param bool $wholecourse If true (default false) then, when necessary to
802 * fill the cache, retrieves information from the entire course not just for
803 * this one activity
804 * @param int $userid User ID or 0 (default) for current user
117bd748
PS
805 * @param array $modinfo Supply the value here - this is used for unit
806 * testing and so that it can be called recursively from within
82bd6a5e 807 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
808 * Otherwise the method calls get_fast_modinfo itself.
4e781c7b 809 * @return object Completion data (record from course_modules_completion)
4e781c7b 810 */
836375ec 811 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
0d5d12bd 812 global $USER, $CFG, $SESSION, $DB;
d7d87535 813
814 // Get user ID
0d5d12bd 815 if (!$userid) {
816 $userid = $USER->id;
4e781c7b 817 }
0d5d12bd 818
4e781c7b 819 // Is this the current user?
0d5d12bd 820 $currentuser = $userid==$USER->id;
821
2be4d090 822 if ($currentuser && is_object($SESSION)) {
0d5d12bd 823 // Make sure cache is present and is for current user (loginas
49f6e5f4 824 // changes this)
0d5d12bd 825 if (!isset($SESSION->completioncache) || $SESSION->completioncacheuserid!=$USER->id) {
826 $SESSION->completioncache = array();
827 $SESSION->completioncacheuserid = $USER->id;
4e781c7b 828 }
829 // Expire any old data from cache
0d5d12bd 830 foreach ($SESSION->completioncache as $courseid=>$activities) {
831 if (empty($activities['updated']) || $activities['updated'] < time()-COMPLETION_CACHE_EXPIRY) {
4e781c7b 832 unset($SESSION->completioncache[$courseid]);
833 }
834 }
835 // See if requested data is present, if so use cache to get it
0d5d12bd 836 if (isset($SESSION->completioncache) &&
837 array_key_exists($this->course->id, $SESSION->completioncache) &&
838 array_key_exists($cm->id, $SESSION->completioncache[$this->course->id])) {
839 return $SESSION->completioncache[$this->course->id][$cm->id];
4e781c7b 840 }
841 }
0d5d12bd 842
4e781c7b 843 // Not there, get via SQL
0d5d12bd 844 if ($currentuser && $wholecourse) {
4e781c7b 845 // Get whole course data for cache
0d5d12bd 846 $alldatabycmc = $DB->get_records_sql("
4e781c7b 847 SELECT
848 cmc.*
849 FROM
49f6e5f4 850 {course_modules} cm
851 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
0d5d12bd 852 WHERE
853 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
854
4e781c7b 855 // Reindex by cm id
0d5d12bd 856 $alldata = array();
857 if ($alldatabycmc) {
858 foreach ($alldatabycmc as $data) {
859 $alldata[$data->coursemoduleid] = $data;
4e781c7b 860 }
861 }
0d5d12bd 862
4e781c7b 863 // Get the module info and build up condition info for each one
0d5d12bd 864 if (empty($modinfo)) {
865 $modinfo = get_fast_modinfo($this->course, $userid);
4e781c7b 866 }
0d5d12bd 867 foreach ($modinfo->cms as $othercm) {
868 if (array_key_exists($othercm->id, $alldata)) {
869 $data = $alldata[$othercm->id];
4e781c7b 870 } else {
871 // Row not present counts as 'not complete'
0d5d12bd 872 $data = new StdClass;
873 $data->id = 0;
874 $data->coursemoduleid = $othercm->id;
875 $data->userid = $userid;
876 $data->completionstate = 0;
877 $data->viewed = 0;
878 $data->timemodified = 0;
4e781c7b 879 }
0d5d12bd 880 $SESSION->completioncache[$this->course->id][$othercm->id] = $data;
4e781c7b 881 }
0d5d12bd 882 $SESSION->completioncache[$this->course->id]['updated'] = time();
883
884 if (!isset($SESSION->completioncache[$this->course->id][$cm->id])) {
4e781c7b 885 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
886 }
887 return $SESSION->completioncache[$this->course->id][$cm->id];
d7d87535 888
4e781c7b 889 } else {
890 // Get single record
0d5d12bd 891 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
892 if ($data == false) {
4e781c7b 893 // Row not present counts as 'not complete'
0d5d12bd 894 $data = new StdClass;
895 $data->id = 0;
896 $data->coursemoduleid = $cm->id;
897 $data->userid = $userid;
898 $data->completionstate = 0;
899 $data->viewed = 0;
900 $data->timemodified = 0;
4e781c7b 901 }
0d5d12bd 902
4e781c7b 903 // Put in cache
0d5d12bd 904 if ($currentuser) {
905 $SESSION->completioncache[$this->course->id][$cm->id] = $data;
4e781c7b 906 // For single updates, only set date if it was empty before
0d5d12bd 907 if (empty($SESSION->completioncache[$this->course->id]['updated'])) {
908 $SESSION->completioncache[$this->course->id]['updated'] = time();
4e781c7b 909 }
910 }
911 }
0d5d12bd 912
4e781c7b 913 return $data;
914 }
0d5d12bd 915
4e781c7b 916 /**
0d5d12bd 917 * Updates completion data for a particular coursemodule and user (user is
4e781c7b 918 * determined from $data).
117bd748 919 *
4e781c7b 920 * (Internal function. Not private, so we can unit-test it.)
0d5d12bd 921 *
836375ec
SH
922 * @param stdClass|cm_info $cm Activity
923 * @param stdClass $data Data about completion for that user
4e781c7b 924 */
836375ec 925 public function internal_set_data($cm, $data) {
0d5d12bd 926 global $USER, $SESSION, $DB;
d7d87535 927
a854bca3 928 $transaction = $DB->start_delegated_transaction();
929 if (!$data->id) {
930 // Check there isn't really a row
931 $data->id = $DB->get_field('course_modules_completion', 'id',
932 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
933 }
934 if (!$data->id) {
4e781c7b 935 // Didn't exist before, needs creating
0d5d12bd 936 $data->id = $DB->insert_record('course_modules_completion', $data);
a854bca3 937 } else {
938 // Has real (nonzero) id meaning that a database row exists, update
939 $DB->update_record('course_modules_completion', $data);
4e781c7b 940 }
a854bca3 941 $transaction->allow_commit();
d7d87535 942
0d5d12bd 943 if ($data->userid == $USER->id) {
944 $SESSION->completioncache[$cm->course][$cm->id] = $data;
6553cda7 945 $reset = 'reset';
946 get_fast_modinfo($reset);
4e781c7b 947 }
948 }
0d5d12bd 949
4e781c7b 950 /**
0d5d12bd 951 * Obtains a list of activities for which completion is enabled on the
4e781c7b 952 * course. The list is ordered by the section order of those activities.
09639ded 953 *
0d5d12bd 954 * @param array $modinfo For unit testing only, supply the value
4e781c7b 955 * here. Otherwise the method calls get_fast_modinfo
956 * @return array Array from $cmid => $cm of all activities with completion enabled,
957 * empty array if none
958 */
959 public function get_activities($modinfo=null) {
960 global $DB;
0d5d12bd 961
4e781c7b 962 // Obtain those activities which have completion turned on
0d5d12bd 963 $withcompletion = $DB->get_records_select('course_modules', 'course='.$this->course->id.
4e781c7b 964 ' AND completion<>'.COMPLETION_TRACKING_NONE);
2be4d090 965 if (!$withcompletion) {
4e781c7b 966 return array();
967 }
0d5d12bd 968
4e781c7b 969 // Use modinfo to get section order and also add in names
0d5d12bd 970 if (empty($modinfo)) {
971 $modinfo = get_fast_modinfo($this->course);
972 }
973 $result = array();
974 foreach ($modinfo->sections as $sectioncms) {
975 foreach ($sectioncms as $cmid) {
976 if (array_key_exists($cmid, $withcompletion)) {
977 $result[$cmid] = $withcompletion[$cmid];
978 $result[$cmid]->modname = $modinfo->cms[$cmid]->modname;
979 $result[$cmid]->name = $modinfo->cms[$cmid]->name;
4e781c7b 980 }
981 }
982 }
0d5d12bd 983
4e781c7b 984 return $result;
985 }
0d5d12bd 986
4e781c7b 987 /**
24a3b341
AB
988 * Checks to see if the userid supplied has a tracked role in
989 * this course
09639ded 990 *
836375ec
SH
991 * @param int $userid User id
992 * @return bool
4e781c7b 993 */
836375ec 994 public function is_tracked_user($userid) {
24a3b341
AB
995 global $DB;
996
5642a8e5
AB
997 $tracked = $this->generate_tracked_user_sql();
998
24a3b341 999 $sql = "SELECT u.id ";
5642a8e5 1000 $sql .= $tracked->sql;
c4a88609 1001 $sql .= ' AND u.id = :userid';
5642a8e5
AB
1002
1003 $params = $tracked->data;
c4a88609 1004 $params['userid'] = (int)$userid;
5642a8e5 1005 return $DB->record_exists_sql($sql, $params);
24a3b341
AB
1006 }
1007
24a3b341
AB
1008 /**
1009 * Return number of users whose progress is tracked in this course
1010 *
1011 * Optionally supply a search's where clause, or a group id
1012 *
836375ec
SH
1013 * @param string $where Where clause sql
1014 * @param array $where_params Where clause params
1015 * @param int $groupid Group id
1016 * @return int
24a3b341 1017 */
836375ec 1018 public function get_num_tracked_users($where = '', $where_params = array(), $groupid = 0) {
24a3b341
AB
1019 global $DB;
1020
5642a8e5
AB
1021 $tracked = $this->generate_tracked_user_sql($groupid);
1022
24a3b341 1023 $sql = "SELECT COUNT(u.id) ";
5642a8e5 1024 $sql .= $tracked->sql;
24a3b341
AB
1025
1026 if ($where) {
1027 $sql .= " AND $where";
1028 }
1029
5642a8e5
AB
1030 $params = array_merge($tracked->data, $where_params);
1031 return $DB->count_records_sql($sql, $params);
24a3b341
AB
1032 }
1033
24a3b341
AB
1034 /**
1035 * Return array of users whose progress is tracked in this course
1036 *
1037 * Optionally supply a search's where caluse, group id, sorting, paging
1038 *
836375ec
SH
1039 * @param string $where Where clause sql (optional)
1040 * @param array $where_params Where clause params (optional)
1041 * @param integer $groupid Group ID to restrict to (optional)
1042 * @param string $sort Order by clause (optional)
1043 * @param integer $limitfrom Result start (optional)
1044 * @param integer $limitnum Result max size (optional)
24e14bc7 1045 * @param context $extracontext If set, includes extra user information fields
1046 * as appropriate to display for current user in this context
836375ec 1047 * @return array
24a3b341 1048 */
836375ec 1049 public function get_tracked_users($where = '', $where_params = array(), $groupid = 0,
24e14bc7 1050 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
24a3b341
AB
1051
1052 global $DB;
1053
5642a8e5
AB
1054 $tracked = $this->generate_tracked_user_sql($groupid);
1055 $params = $tracked->data;
1056
24a3b341
AB
1057 $sql = "
1058 SELECT
1059 u.id,
1060 u.firstname,
1061 u.lastname,
1062 u.idnumber
1063 ";
24e14bc7 1064 if ($extracontext) {
1065 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1066 }
24a3b341 1067
5642a8e5 1068 $sql .= $tracked->sql;
24a3b341
AB
1069
1070 if ($where) {
1071 $sql .= " AND $where";
5642a8e5 1072 $params = array_merge($params, $where_params);
24a3b341
AB
1073 }
1074
1075 if ($sort) {
1076 $sql .= " ORDER BY $sort";
1077 }
1078
5642a8e5 1079 $users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
24a3b341
AB
1080 return $users ? $users : array(); // In case it returns false
1081 }
1082
24a3b341
AB
1083 /**
1084 * Generate the SQL for finding tracked users in this course
1085 *
5642a8e5
AB
1086 * Returns an object containing the sql fragment and an array of
1087 * bound data params.
24a3b341 1088 *
836375ec
SH
1089 * @param integer $groupid
1090 * @return stdClass With two properties, sql (string), and data (array)
24a3b341 1091 */
836375ec 1092 public function generate_tracked_user_sql($groupid = 0) {
24a3b341 1093 global $CFG;
d7d87535 1094
5642a8e5
AB
1095 $return = new stdClass();
1096 $return->sql = '';
1097 $return->data = array();
1098
1c6ed505 1099 if (!empty($CFG->gradebookroles)) {
1100 $roles = ' AND ra.roleid IN ('.$CFG->gradebookroles.')';
4e781c7b 1101 } else {
1102 // This causes it to default to everyone (if there is no student role)
24a3b341
AB
1103 $roles = '';
1104 }
1105
1106 // Build context sql
1107 $context = get_context_instance(CONTEXT_COURSE, $this->course->id);
1108 $parentcontexts = substr($context->path, 1); // kill leading slash
1109 $parentcontexts = str_replace('/', ',', $parentcontexts);
1110 if ($parentcontexts !== '') {
1111 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4e781c7b 1112 }
24a3b341
AB
1113
1114 $groupjoin = '';
1115 $groupselect = '';
1116 if ($groupid) {
1117 $groupjoin = "JOIN {groups_members} gm
1118 ON gm.userid = u.id";
5642a8e5 1119 $groupselect = " AND gm.groupid = :groupid ";
caee6e6c 1120
5642a8e5 1121 $return->data['groupid'] = $groupid;
24a3b341
AB
1122 }
1123
5642a8e5 1124 $return->sql = "
24a3b341
AB
1125 FROM
1126 {user} u
1127 INNER JOIN
1128 {role_assignments} ra
1129 ON ra.userid = u.id
1130 INNER JOIN
1131 {role} r
1132 ON r.id = ra.roleid
1133 INNER JOIN
1134 {user_enrolments} ue
1135 ON ue.userid = u.id
1136 INNER JOIN
1137 {enrol} e
1138 ON e.id = ue.enrolid
1139 INNER JOIN
1140 {course} c
1141 ON c.id = e.courseid
1142 $groupjoin
1143 WHERE
5642a8e5
AB
1144 (ra.contextid = :contextid $parentcontexts)
1145 AND c.id = :courseid
24a3b341
AB
1146 AND ue.status = 0
1147 AND e.status = 0
5642a8e5
AB
1148 AND ue.timestart < :now1
1149 AND (ue.timeend > :now2 OR ue.timeend = 0)
24a3b341
AB
1150 $groupselect
1151 $roles
1152 ";
1153
5642a8e5
AB
1154 $now = time();
1155 $return->data['now1'] = $now;
1156 $return->data['now2'] = $now;
1157 $return->data['contextid'] = $context->id;
1158 $return->data['courseid'] = $this->course->id;
1159
1160 return $return;
4e781c7b 1161 }
0d5d12bd 1162
4e781c7b 1163 /**
1164 * Obtains progress information across a course for all users on that course, or
1165 * for all users in a specific group. Intended for use when displaying progress.
117bd748 1166 *
4e781c7b 1167 * This includes only users who, in course context, have one of the roles for
1c6ed505 1168 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
117bd748 1169 *
4e781c7b 1170 * Users are included (in the first array) even if they do not have
1171 * completion progress for any course-module.
1172 *
1173 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1174 * last name
5642a8e5
AB
1175 * @param string $where Where clause sql (optional)
1176 * @param array $where_params Where clause params (optional)
4e781c7b 1177 * @param int $groupid Group ID or 0 (default)/false for all groups
24a3b341
AB
1178 * @param int $pagesize Number of users to actually return (optional)
1179 * @param int $start User to start at if paging (optional)
24e14bc7 1180 * @param context $extracontext If set, includes extra user information fields
1181 * as appropriate to display for current user in this context
836375ec 1182 * @return stdClass with ->total and ->start (same as $start) and ->users;
35da0e87 1183 * an array of user objects (like mdl_user id, firstname, lastname)
4e781c7b 1184 * containing an additional ->progress array of coursemoduleid => completionstate
1185 */
5642a8e5 1186 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
24e14bc7 1187 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
0d5d12bd 1188 global $CFG, $DB;
1189
4e781c7b 1190 // Get list of applicable users
24e14bc7 1191 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1192 $start, $pagesize, $extracontext);
0d5d12bd 1193
1194 // Get progress information for these users in groups of 1, 000 (if needed)
4e781c7b 1195 // to avoid making the SQL IN too long
24a3b341 1196 $results = array();
0d5d12bd 1197 $userids = array();
1198 foreach ($users as $user) {
1199 $userids[] = $user->id;
24a3b341
AB
1200 $results[$user->id] = $user;
1201 $results[$user->id]->progress = array();
0d5d12bd 1202 }
1203
1204 for($i=0; $i<count($userids); $i+=1000) {
1205 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1206
1207 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1208 array_splice($params, 0, 0, array($this->course->id));
1209 $rs = $DB->get_recordset_sql("
24a3b341
AB
1210 SELECT
1211 cmc.*
1212 FROM
1213 {course_modules} cm
1214 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1215 WHERE
836375ec 1216 cm.course=? AND cmc.userid $insql", $params);
0d5d12bd 1217 foreach ($rs as $progress) {
24a3b341
AB
1218 $progress = (object)$progress;
1219 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
4e781c7b 1220 }
1221 $rs->close();
1222 }
0d5d12bd 1223
24a3b341 1224 return $results;
4e781c7b 1225 }
0d5d12bd 1226
09639ded 1227 /**
c4893595
SM
1228 * Called by grade code to inform the completion system when a grade has
1229 * been changed. If the changed grade is used to determine completion for
1230 * the course-module, then the completion status will be updated.
09639ded 1231 *
836375ec 1232 * @param stdClass|cm_info $cm Course-module for item that owns grade
c4893595 1233 * @param grade_item $item Grade item
836375ec 1234 * @param stdClass $grade
09639ded 1235 * @param bool $deleted
09639ded 1236 */
91537a88 1237 public function inform_grade_changed($cm, $item, $grade, $deleted) {
ca6b2d68 1238 // Bail out now if completion is not enabled for course-module, it is enabled
1239 // but is set to manual, grade is not used to compute completion, or this
1240 // is a different numbered grade
0d5d12bd 1241 if (!$this->is_enabled($cm) ||
ca6b2d68 1242 $cm->completion == COMPLETION_TRACKING_MANUAL ||
4e781c7b 1243 is_null($cm->completiongradeitemnumber) ||
0d5d12bd 1244 $item->itemnumber != $cm->completiongradeitemnumber) {
4e781c7b 1245 return;
1246 }
0d5d12bd 1247
4e781c7b 1248 // What is the expected result based on this grade?
0d5d12bd 1249 if ($deleted) {
4e781c7b 1250 // Grade being deleted, so only change could be to make it incomplete
0d5d12bd 1251 $possibleresult = COMPLETION_INCOMPLETE;
4e781c7b 1252 } else {
caee6e6c 1253 $possibleresult = self::internal_get_grade_state($item, $grade);
4e781c7b 1254 }
caee6e6c 1255
4e781c7b 1256 // OK, let's update state based on this
0d5d12bd 1257 $this->update_state($cm, $possibleresult, $grade->userid);
4e781c7b 1258 }
0d5d12bd 1259
4e781c7b 1260 /**
1261 * Calculates the completion state that would result from a graded item
1262 * (where grade-based completion is turned on) based on the actual grade
1263 * and settings.
117bd748 1264 *
09639ded 1265 * Internal function. Not private, so we can unit-test it.
4e781c7b 1266 *
95dd54ee
AA
1267 * @param grade_item $item an instance of grade_item
1268 * @param grade_grade $grade an instance of grade_grade
4e781c7b 1269 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1270 */
caee6e6c 1271 public static function internal_get_grade_state($item, $grade) {
0d5d12bd 1272 if (!$grade) {
4e781c7b 1273 return COMPLETION_INCOMPLETE;
1274 }
1275 // Conditions to show pass/fail:
1276 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1277 // b) Grade is visible (neither hidden nor hidden-until)
0d5d12bd 1278 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
4e781c7b 1279 // Use final grade if set otherwise raw grade
0d5d12bd 1280 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1281
4e781c7b 1282 // We are displaying and tracking pass/fail
0d5d12bd 1283 if ($score >= $item->gradepass) {
4e781c7b 1284 return COMPLETION_COMPLETE_PASS;
1285 } else {
1286 return COMPLETION_COMPLETE_FAIL;
1287 }
1288 } else {
fd546aaa
SM
1289 // Not displaying pass/fail, so just if there is a grade
1290 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1291 // Grade exists, so maybe complete now
1292 return COMPLETION_COMPLETE;
1293 } else {
1294 // Grade does not exist, so maybe incomplete now
1295 return COMPLETION_INCOMPLETE;
1296 }
4e781c7b 1297 }
1298 }
0d5d12bd 1299
94db2749
AB
1300 /**
1301 * Aggregate activity completion state
1302 *
1303 * @param int $type Aggregation type (COMPLETION_* constant)
1304 * @param bool $old Old state
1305 * @param bool $new New state
1306 * @return bool
1307 */
1308 public static function aggregate_completion_states($type, $old, $new) {
1309 if ($type == COMPLETION_AND) {
1310 return $old && $new;
1311 } else {
1312 return $old || $new;
1313 }
1314 }
1315
4e781c7b 1316 /**
4e781c7b 1317 * This is to be used only for system errors (things that shouldn't happen)
1318 * and not user-level errors.
1319 *
836375ec
SH
1320 * @global type $CFG
1321 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1322 * @throws moodle_exception Exception with the error string as debug info
4e781c7b 1323 */
836375ec 1324 public function internal_systemerror($error) {
4e781c7b 1325 global $CFG;
82bd6a5e 1326 throw new moodle_exception('err_system','completion',
1327 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1328 }
d7d87535 1329
117bd748
PS
1330 /**
1331 * For testing only. Wipes information cached in user session.
09639ded 1332 */
836375ec 1333 public static function wipe_session_cache() {
82bd6a5e 1334 global $SESSION;
1335 unset($SESSION->completioncache);
1336 unset($SESSION->completioncacheuserid);
4e781c7b 1337 }
7142a755 1338}