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