Merge branch 'MDL-73502' of https://github.com/stronk7/moodle
[moodle.git] / lib / completionlib.php
blob77c34bad9cf677cec09c828105ab6b442ff088bd
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
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/>.
17 /**
18 * Contains classes, functions and constants used during the tracking
19 * of activity completion for users.
21 * Completion top-level options (admin setting enablecompletion)
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
29 use core_completion\activity_custom_completion;
31 defined('MOODLE_INTERNAL') || die();
33 /**
34 * Include the required completion libraries
36 require_once $CFG->dirroot.'/completion/completion_aggregation.php';
37 require_once $CFG->dirroot.'/completion/criteria/completion_criteria.php';
38 require_once $CFG->dirroot.'/completion/completion_completion.php';
39 require_once $CFG->dirroot.'/completion/completion_criteria_completion.php';
42 /**
43 * The completion system is enabled in this site/course
45 define('COMPLETION_ENABLED', 1);
46 /**
47 * The completion system is not enabled in this site/course
49 define('COMPLETION_DISABLED', 0);
51 /**
52 * Completion tracking is disabled for this activity
53 * This is a completion tracking option per-activity (course_modules/completion)
55 define('COMPLETION_TRACKING_NONE', 0);
57 /**
58 * Manual completion tracking (user ticks box) is enabled for this activity
59 * This is a completion tracking option per-activity (course_modules/completion)
61 define('COMPLETION_TRACKING_MANUAL', 1);
62 /**
63 * Automatic completion tracking (system ticks box) is enabled for this activity
64 * This is a completion tracking option per-activity (course_modules/completion)
66 define('COMPLETION_TRACKING_AUTOMATIC', 2);
68 /**
69 * The user has not completed this activity.
70 * This is a completion state value (course_modules_completion/completionstate)
72 define('COMPLETION_INCOMPLETE', 0);
73 /**
74 * The user has completed this activity. It is not specified whether they have
75 * passed or failed it.
76 * This is a completion state value (course_modules_completion/completionstate)
78 define('COMPLETION_COMPLETE', 1);
79 /**
80 * The user has completed this activity with a grade above the pass mark.
81 * This is a completion state value (course_modules_completion/completionstate)
83 define('COMPLETION_COMPLETE_PASS', 2);
84 /**
85 * The user has completed this activity but their grade is less than the pass mark
86 * This is a completion state value (course_modules_completion/completionstate)
88 define('COMPLETION_COMPLETE_FAIL', 3);
90 /**
91 * The effect of this change to completion status is unknown.
92 * A completion effect changes (used only in update_state)
94 define('COMPLETION_UNKNOWN', -1);
95 /**
96 * The user's grade has changed, so their new state might be
97 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
98 * A completion effect changes (used only in update_state)
100 define('COMPLETION_GRADECHANGE', -2);
103 * User must view this activity.
104 * Whether view is required to create an activity (course_modules/completionview)
106 define('COMPLETION_VIEW_REQUIRED', 1);
108 * User does not need to view this activity
109 * Whether view is required to create an activity (course_modules/completionview)
111 define('COMPLETION_VIEW_NOT_REQUIRED', 0);
114 * User has viewed this activity.
115 * Completion viewed state (course_modules_completion/viewed)
117 define('COMPLETION_VIEWED', 1);
119 * User has not viewed this activity.
120 * Completion viewed state (course_modules_completion/viewed)
122 define('COMPLETION_NOT_VIEWED', 0);
125 * Completion details should be ORed together and you should return false if
126 * none apply.
128 define('COMPLETION_OR', false);
130 * Completion details should be ANDed together and you should return true if
131 * none apply
133 define('COMPLETION_AND', true);
136 * Course completion criteria aggregation method.
138 define('COMPLETION_AGGREGATION_ALL', 1);
140 * Course completion criteria aggregation method.
142 define('COMPLETION_AGGREGATION_ANY', 2);
145 * Completion conditions will be displayed to user.
147 define('COMPLETION_SHOW_CONDITIONS', 1);
150 * Completion conditions will be hidden from user.
152 define('COMPLETION_HIDE_CONDITIONS', 0);
155 * Utility function for checking if the logged in user can view
156 * another's completion data for a particular course
158 * @access public
159 * @param int $userid Completion data's owner
160 * @param mixed $course Course object or Course ID (optional)
161 * @return boolean
163 function completion_can_view_data($userid, $course = null) {
164 global $USER;
166 if (!isloggedin()) {
167 return false;
170 if (!is_object($course)) {
171 $cid = $course;
172 $course = new stdClass();
173 $course->id = $cid;
176 // Check if this is the site course
177 if ($course->id == SITEID) {
178 $course = null;
181 // Check if completion is enabled
182 if ($course) {
183 $cinfo = new completion_info($course);
184 if (!$cinfo->is_enabled()) {
185 return false;
187 } else {
188 if (!completion_info::is_enabled_for_site()) {
189 return false;
193 // Is own user's data?
194 if ($USER->id == $userid) {
195 return true;
198 // Check capabilities
199 $personalcontext = context_user::instance($userid);
201 if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
202 return true;
203 } elseif (has_capability('report/completion:view', $personalcontext)) {
204 return true;
207 if ($course->id) {
208 $coursecontext = context_course::instance($course->id);
209 } else {
210 $coursecontext = context_system::instance();
213 if (has_capability('report/completion:view', $coursecontext)) {
214 return true;
217 return false;
222 * Class represents completion information for a course.
224 * Does not contain any data, so you can safely construct it multiple times
225 * without causing any problems.
227 * @package core
228 * @category completion
229 * @copyright 2008 Sam Marshall
230 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
232 class completion_info {
234 /* @var stdClass Course object passed during construction */
235 private $course;
237 /* @var int Course id */
238 public $course_id;
240 /* @var array Completion criteria {@link completion_info::get_criteria()} */
241 private $criteria;
244 * Return array of aggregation methods
245 * @return array
247 public static function get_aggregation_methods() {
248 return array(
249 COMPLETION_AGGREGATION_ALL => get_string('all'),
250 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
255 * Constructs with course details.
257 * When instantiating a new completion info object you must provide a course
258 * object with at least id, and enablecompletion properties. Property
259 * cacherev is needed if you check completion of the current user since
260 * it is used for cache validation.
262 * @param stdClass $course Moodle course object.
264 public function __construct($course) {
265 $this->course = $course;
266 $this->course_id = $course->id;
270 * Determines whether completion is enabled across entire site.
272 * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
273 * COMPLETION_DISABLED (false) if it's complete
275 public static function is_enabled_for_site() {
276 global $CFG;
277 return !empty($CFG->enablecompletion);
281 * Checks whether completion is enabled in a particular course and possibly
282 * activity.
284 * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
285 * completion enable state.
286 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
287 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
288 * for a course-module.
290 public function is_enabled($cm = null) {
291 global $CFG, $DB;
293 // First check global completion
294 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
295 return COMPLETION_DISABLED;
298 // Load data if we do not have enough
299 if (!isset($this->course->enablecompletion)) {
300 $this->course = get_course($this->course_id);
303 // Check course completion
304 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
305 return COMPLETION_DISABLED;
308 // If there was no $cm and we got this far, then it's enabled
309 if (!$cm) {
310 return COMPLETION_ENABLED;
313 // Return course-module completion value
314 return $cm->completion;
318 * Displays the 'Your progress' help icon, if completion tracking is enabled.
319 * Just prints the result of display_help_icon().
321 * @deprecated since Moodle 2.0 - Use display_help_icon instead.
323 public function print_help_icon() {
324 debugging('The function print_help_icon() is deprecated, please do not use it anymore.',
325 DEBUG_DEVELOPER);
326 print $this->display_help_icon();
330 * Returns the 'Your progress' help icon, if completion tracking is enabled.
332 * @return string HTML code for help icon, or blank if not needed
333 * @deprecated since Moodle 4.0 - The 'Your progress' info isn't displayed any more.
335 public function display_help_icon() {
336 global $PAGE, $OUTPUT, $USER;
337 debugging('The function display_help_icon() is deprecated, please do not use it anymore.',
338 DEBUG_DEVELOPER);
339 $result = '';
340 if ($this->is_enabled() && !$PAGE->user_is_editing() && $this->is_tracked_user($USER->id) && isloggedin() &&
341 !isguestuser()) {
342 $result .= html_writer::tag('div', get_string('yourprogress','completion') .
343 $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
344 'class' => 'completionprogress'));
346 return $result;
350 * Get a course completion for a user
352 * @param int $user_id User id
353 * @param int $criteriatype Specific criteria type to return
354 * @return bool|completion_criteria_completion returns false on fail
356 public function get_completion($user_id, $criteriatype) {
357 $completions = $this->get_completions($user_id, $criteriatype);
359 if (empty($completions)) {
360 return false;
361 } elseif (count($completions) > 1) {
362 print_error('multipleselfcompletioncriteria', 'completion');
365 return $completions[0];
369 * Get all course criteria's completion objects for a user
371 * @param int $user_id User id
372 * @param int $criteriatype Specific criteria type to return (optional)
373 * @return array
375 public function get_completions($user_id, $criteriatype = null) {
376 $criteria = $this->get_criteria($criteriatype);
378 $completions = array();
380 foreach ($criteria as $criterion) {
381 $params = array(
382 'course' => $this->course_id,
383 'userid' => $user_id,
384 'criteriaid' => $criterion->id
387 $completion = new completion_criteria_completion($params);
388 $completion->attach_criteria($criterion);
390 $completions[] = $completion;
393 return $completions;
397 * Get completion object for a user and a criteria
399 * @param int $user_id User id
400 * @param completion_criteria $criteria Criteria object
401 * @return completion_criteria_completion
403 public function get_user_completion($user_id, $criteria) {
404 $params = array(
405 'course' => $this->course_id,
406 'userid' => $user_id,
407 'criteriaid' => $criteria->id,
410 $completion = new completion_criteria_completion($params);
411 return $completion;
415 * Check if course has completion criteria set
417 * @return bool Returns true if there are criteria
419 public function has_criteria() {
420 $criteria = $this->get_criteria();
422 return (bool) count($criteria);
426 * Get course completion criteria
428 * @param int $criteriatype Specific criteria type to return (optional)
430 public function get_criteria($criteriatype = null) {
432 // Fill cache if empty
433 if (!is_array($this->criteria)) {
434 global $DB;
436 $params = array(
437 'course' => $this->course->id
440 // Load criteria from database
441 $records = (array)$DB->get_records('course_completion_criteria', $params);
443 // Order records so activities are in the same order as they appear on the course view page.
444 if ($records) {
445 $activitiesorder = array_keys(get_fast_modinfo($this->course)->get_cms());
446 usort($records, function ($a, $b) use ($activitiesorder) {
447 $aidx = ($a->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
448 array_search($a->moduleinstance, $activitiesorder) : false;
449 $bidx = ($b->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
450 array_search($b->moduleinstance, $activitiesorder) : false;
451 if ($aidx === false || $bidx === false || $aidx == $bidx) {
452 return 0;
454 return ($aidx < $bidx) ? -1 : 1;
458 // Build array of criteria objects
459 $this->criteria = array();
460 foreach ($records as $record) {
461 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
465 // If after all criteria
466 if ($criteriatype === null) {
467 return $this->criteria;
470 // If we are only after a specific criteria type
471 $criteria = array();
472 foreach ($this->criteria as $criterion) {
474 if ($criterion->criteriatype != $criteriatype) {
475 continue;
478 $criteria[$criterion->id] = $criterion;
481 return $criteria;
485 * Get aggregation method
487 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
488 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
490 public function get_aggregation_method($criteriatype = null) {
491 $params = array(
492 'course' => $this->course_id,
493 'criteriatype' => $criteriatype
496 $aggregation = new completion_aggregation($params);
498 if (!$aggregation->id) {
499 $aggregation->method = COMPLETION_AGGREGATION_ALL;
502 return $aggregation->method;
506 * @deprecated since Moodle 2.8 MDL-46290.
508 public function get_incomplete_criteria() {
509 throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
513 * Clear old course completion criteria
515 public function clear_criteria() {
516 global $DB;
518 // Remove completion criteria records for the course itself, and any records that refer to the course.
519 $select = 'course = :course OR (criteriatype = :type AND courseinstance = :courseinstance)';
520 $params = [
521 'course' => $this->course_id,
522 'type' => COMPLETION_CRITERIA_TYPE_COURSE,
523 'courseinstance' => $this->course_id,
526 $DB->delete_records_select('course_completion_criteria', $select, $params);
527 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
529 $this->delete_course_completion_data();
533 * Has the supplied user completed this course
535 * @param int $user_id User's id
536 * @return boolean
538 public function is_course_complete($user_id) {
539 $params = array(
540 'userid' => $user_id,
541 'course' => $this->course_id
544 $ccompletion = new completion_completion($params);
545 return $ccompletion->is_complete();
549 * Check whether the supplied user can override the activity completion statuses within the current course.
551 * @param stdClass $user The user object.
552 * @return bool True if the user can override, false otherwise.
554 public function user_can_override_completion($user) {
555 return has_capability('moodle/course:overridecompletion', context_course::instance($this->course_id), $user);
559 * Updates (if necessary) the completion state of activity $cm for the given
560 * user.
562 * For manual completion, this function is called when completion is toggled
563 * with $possibleresult set to the target state.
565 * For automatic completion, this function should be called every time a module
566 * does something which might influence a user's completion state. For example,
567 * if a forum provides options for marking itself 'completed' once a user makes
568 * N posts, this function should be called every time a user makes a new post.
569 * [After the post has been saved to the database]. When calling, you do not
570 * need to pass in the new completion state. Instead this function carries out completion
571 * calculation by checking grades and viewed state itself, and calling the involved module
572 * via mod_{modulename}\\completion\\custom_completion::get_overall_completion_state() to
573 * check module-specific conditions.
575 * @param stdClass|cm_info $cm Course-module
576 * @param int $possibleresult Expected completion result. If the event that
577 * has just occurred (e.g. add post) can only result in making the activity
578 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
579 * has just occurred (e.g. delete post) can only result in making the activity
580 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
581 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
582 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
583 * processing early if the user's completion state already matches the expected
584 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
585 * must be used; these directly set the specified state.
586 * @param int $userid User ID to be updated. Default 0 = current user
587 * @param bool $override Whether manually overriding the existing completion state.
588 * @param bool $isbulkupdate If bulk grade update is happening.
589 * @return void
590 * @throws moodle_exception if trying to override without permission.
592 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0,
593 $override = false, $isbulkupdate = false) {
594 global $USER;
596 // Do nothing if completion is not enabled for that activity
597 if (!$this->is_enabled($cm)) {
598 return;
601 // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
602 if ($override) {
603 if (!$this->user_can_override_completion($USER)) {
604 throw new required_capability_exception(context_course::instance($this->course_id),
605 'moodle/course:overridecompletion', 'nopermission', '');
609 // Default to current user if one is not provided.
610 if ($userid == 0) {
611 $userid = $USER->id;
614 // Delete the cm's cached completion data for this user if automatic completion is enabled.
615 // This ensures any changes to the status of individual completion conditions in the activity will be fetched.
616 if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC) {
617 $completioncache = cache::make('core', 'completion');
618 $completionkey = $userid . '_' . $this->course->id;
619 $completiondata = $completioncache->get($completionkey);
621 if ($completiondata !== false) {
622 unset($completiondata[$cm->id]);
623 $completioncache->set($completionkey, $completiondata);
627 // Get current value of completion state and do nothing if it's same as
628 // the possible result of this change. If the change is to COMPLETE and the
629 // current value is one of the COMPLETE_xx subtypes, ignore that as well
630 $current = $this->get_data($cm, false, $userid);
631 if ($possibleresult == $current->completionstate ||
632 ($possibleresult == COMPLETION_COMPLETE &&
633 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
634 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
635 return;
638 // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
639 // unless processing another override.
640 // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
641 // overridden to INCOMPLETE to still be processed by normal completion triggers.
642 if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC && !is_null($current->overrideby)
643 && $current->completionstate == COMPLETION_COMPLETE && !$override) {
644 return;
647 // For manual tracking, or if overriding the completion state, we set the state directly.
648 if ($cm->completion == COMPLETION_TRACKING_MANUAL || $override) {
649 switch($possibleresult) {
650 case COMPLETION_COMPLETE:
651 case COMPLETION_INCOMPLETE:
652 $newstate = $possibleresult;
653 break;
654 default:
655 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
658 } else {
659 $newstate = $this->internal_get_state($cm, $userid, $current);
662 // If the overall completion state has changed, update it in the cache.
663 if ($newstate != $current->completionstate) {
664 $current->completionstate = $newstate;
665 $current->timemodified = time();
666 $current->overrideby = $override ? $USER->id : null;
667 $this->internal_set_data($cm, $current, $isbulkupdate);
672 * Calculates the completion state for an activity and user.
674 * Internal function. Not private, so we can unit-test it.
676 * @param stdClass|cm_info $cm Activity
677 * @param int $userid ID of user
678 * @param stdClass $current Previous completion information from database
679 * @return mixed
681 public function internal_get_state($cm, $userid, $current) {
682 global $USER, $DB;
684 // Get user ID
685 if (!$userid) {
686 $userid = $USER->id;
689 $newstate = COMPLETION_COMPLETE;
690 if ($cm instanceof stdClass) {
691 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it.
692 if (!isset($cm->modname)) {
693 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
695 // Some functions call this method and pass $cm as an object with ID only. Make sure course is set as well.
696 if (!isset($cm->course)) {
697 $cm->course = $this->course_id;
700 // Make sure we're using a cm_info object.
701 $cminfo = cm_info::create($cm, $userid);
702 $completionstate = $this->get_core_completion_state($cminfo, $userid);
704 if (plugin_supports('mod', $cminfo->modname, FEATURE_COMPLETION_HAS_RULES)) {
705 $response = true;
706 $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cminfo->modname);
707 if ($cmcompletionclass) {
708 /** @var activity_custom_completion $cmcompletion */
709 $cmcompletion = new $cmcompletionclass($cminfo, $userid, $completionstate);
710 $response = $cmcompletion->get_overall_completion_state() != COMPLETION_INCOMPLETE;
711 } else {
712 // Fallback to the get_completion_state callback.
713 $cmcompletionclass = "mod_{$cminfo->modname}\\completion\\custom_completion";
714 $function = $cminfo->modname . '_get_completion_state';
715 if (!function_exists($function)) {
716 $this->internal_systemerror("Module {$cminfo->modname} claims to support FEATURE_COMPLETION_HAS_RULES " .
717 "but does not implement the custom completion class $cmcompletionclass which extends " .
718 "\core_completion\activity_custom_completion.");
720 debugging("*_get_completion_state() callback functions such as $function have been deprecated and should no " .
721 "longer be used. Please implement the custom completion class $cmcompletionclass which extends " .
722 "\core_completion\activity_custom_completion.", DEBUG_DEVELOPER);
723 $response = $function($this->course, $cm, $userid, COMPLETION_AND, $completionstate);
726 if (!$response) {
727 return COMPLETION_INCOMPLETE;
731 if ($completionstate) {
732 // We have allowed the plugins to do it's thing and run their own checks.
733 // We have now reached a state where we need to AND all the calculated results.
734 // Preference for COMPLETION_COMPLETE_PASS over COMPLETION_COMPLETE for proper indication in reports.
735 $newstate = array_reduce($completionstate, function($carry, $value) {
736 if (in_array(COMPLETION_INCOMPLETE, [$carry, $value])) {
737 return COMPLETION_INCOMPLETE;
738 } else if (in_array(COMPLETION_COMPLETE_FAIL, [$carry, $value])) {
739 return COMPLETION_COMPLETE_FAIL;
740 } else {
741 return in_array(COMPLETION_COMPLETE_PASS, [$carry, $value]) ? COMPLETION_COMPLETE_PASS : $value;
744 }, COMPLETION_COMPLETE);
747 return $newstate;
752 * Fetches the completion state for an activity completion's require grade completion requirement.
754 * @param cm_info $cm The course module information.
755 * @param int $userid The user ID.
756 * @return int The completion state.
758 public function get_grade_completion(cm_info $cm, int $userid): int {
759 global $CFG;
761 require_once($CFG->libdir . '/gradelib.php');
762 $item = grade_item::fetch([
763 'courseid' => $cm->course,
764 'itemtype' => 'mod',
765 'itemmodule' => $cm->modname,
766 'iteminstance' => $cm->instance,
767 'itemnumber' => $cm->completiongradeitemnumber
769 if ($item) {
770 // Fetch 'grades' (will be one or none).
771 $grades = grade_grade::fetch_users_grades($item, [$userid], false);
772 if (empty($grades)) {
773 // No grade for user.
774 return COMPLETION_INCOMPLETE;
776 if (count($grades) > 1) {
777 $this->internal_systemerror("Unexpected result: multiple grades for
778 item '{$item->id}', user '{$userid}'");
780 return self::internal_get_grade_state($item, reset($grades));
783 return COMPLETION_INCOMPLETE;
787 * Marks a module as viewed.
789 * Should be called whenever a module is 'viewed' (it is up to the module how to
790 * determine that). Has no effect if viewing is not set as a completion condition.
792 * Note that this function must be called before you print the page header because
793 * it is possible that the navigation block may depend on it. If you call it after
794 * printing the header, it shows a developer debug warning.
796 * @param stdClass|cm_info $cm Activity
797 * @param int $userid User ID or 0 (default) for current user
798 * @return void
800 public function set_module_viewed($cm, $userid=0) {
801 global $PAGE;
802 if ($PAGE->headerprinted) {
803 debugging('set_module_viewed must be called before header is printed',
804 DEBUG_DEVELOPER);
807 // Don't do anything if view condition is not turned on
808 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
809 return;
812 // Get current completion state
813 $data = $this->get_data($cm, false, $userid);
815 // If we already viewed it, don't do anything unless the completion status is overridden.
816 // If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
817 if ($data->viewed == COMPLETION_VIEWED && empty($data->overrideby)) {
818 return;
821 // OK, change state, save it, and update completion
822 $data->viewed = COMPLETION_VIEWED;
823 $this->internal_set_data($cm, $data);
824 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
828 * Determines how much completion data exists for an activity. This is used when
829 * deciding whether completion information should be 'locked' in the module
830 * editing form.
832 * @param cm_info $cm Activity
833 * @return int The number of users who have completion data stored for this
834 * activity, 0 if none
836 public function count_user_data($cm) {
837 global $DB;
839 return $DB->get_field_sql("
840 SELECT
841 COUNT(1)
842 FROM
843 {course_modules_completion}
844 WHERE
845 coursemoduleid=? AND completionstate<>0", array($cm->id));
849 * Determines how much course completion data exists for a course. This is used when
850 * deciding whether completion information should be 'locked' in the completion
851 * settings form and activity completion settings.
853 * @param int $user_id Optionally only get course completion data for a single user
854 * @return int The number of users who have completion data stored for this
855 * course, 0 if none
857 public function count_course_user_data($user_id = null) {
858 global $DB;
860 $sql = '
861 SELECT
862 COUNT(1)
863 FROM
864 {course_completion_crit_compl}
865 WHERE
866 course = ?
869 $params = array($this->course_id);
871 // Limit data to a single user if an ID is supplied
872 if ($user_id) {
873 $sql .= ' AND userid = ?';
874 $params[] = $user_id;
877 return $DB->get_field_sql($sql, $params);
881 * Check if this course's completion criteria should be locked
883 * @return boolean
885 public function is_course_locked() {
886 return (bool) $this->count_course_user_data();
890 * Deletes all course completion completion data.
892 * Intended to be used when unlocking completion criteria settings.
894 public function delete_course_completion_data() {
895 global $DB;
897 $DB->delete_records('course_completions', array('course' => $this->course_id));
898 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
900 // Difficult to find affected users, just purge all completion cache.
901 cache::make('core', 'completion')->purge();
902 cache::make('core', 'coursecompletion')->purge();
906 * Deletes all activity and course completion data for an entire course
907 * (the below delete_all_state function does this for a single activity).
909 * Used by course reset page.
911 public function delete_all_completion_data() {
912 global $DB;
914 // Delete from database.
915 $DB->delete_records_select('course_modules_completion',
916 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
917 array($this->course_id));
919 // Wipe course completion data too.
920 $this->delete_course_completion_data();
924 * Deletes completion state related to an activity for all users.
926 * Intended for use only when the activity itself is deleted.
928 * @param stdClass|cm_info $cm Activity
930 public function delete_all_state($cm) {
931 global $DB;
933 // Delete from database
934 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
936 // Check if there is an associated course completion criteria
937 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
938 $acriteria = false;
939 foreach ($criteria as $criterion) {
940 if ($criterion->moduleinstance == $cm->id) {
941 $acriteria = $criterion;
942 break;
946 if ($acriteria) {
947 // Delete all criteria completions relating to this activity
948 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
949 $DB->delete_records('course_completions', array('course' => $this->course_id));
952 // Difficult to find affected users, just purge all completion cache.
953 cache::make('core', 'completion')->purge();
954 cache::make('core', 'coursecompletion')->purge();
958 * Recalculates completion state related to an activity for all users.
960 * Intended for use if completion conditions change. (This should be avoided
961 * as it may cause some things to become incomplete when they were previously
962 * complete, with the effect - for example - of hiding a later activity that
963 * was previously available.)
965 * Resetting state of manual tickbox has same result as deleting state for
966 * it.
968 * @param stcClass|cm_info $cm Activity
970 public function reset_all_state($cm) {
971 global $DB;
973 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
974 $this->delete_all_state($cm);
975 return;
977 // Get current list of users with completion state
978 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
979 $keepusers = array();
980 foreach ($rs as $rec) {
981 $keepusers[] = $rec->userid;
983 $rs->close();
985 // Delete all existing state.
986 $this->delete_all_state($cm);
988 // Merge this with list of planned users (according to roles)
989 $trackedusers = $this->get_tracked_users();
990 foreach ($trackedusers as $trackeduser) {
991 $keepusers[] = $trackeduser->id;
993 $keepusers = array_unique($keepusers);
995 // Recalculate state for each kept user
996 foreach ($keepusers as $keepuser) {
997 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
1002 * Obtains completion data for a particular activity and user (from the
1003 * completion cache if available, or by SQL query)
1005 * @param stdClass|cm_info $cm Activity; only required field is ->id
1006 * @param bool $wholecourse If true (default false) then, when necessary to
1007 * fill the cache, retrieves information from the entire course not just for
1008 * this one activity
1009 * @param int $userid User ID or 0 (default) for current user
1010 * @param array $modinfo Supply the value here - this is used for unit
1011 * testing and so that it can be called recursively from within
1012 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
1013 * Otherwise the method calls get_fast_modinfo itself.
1014 * @return object Completion data. Record from course_modules_completion plus other completion statuses such as
1015 * - Completion status for 'must-receive-grade' completion rule.
1016 * - Custom completion statuses defined by the activity module plugin.
1018 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
1019 global $USER, $DB;
1020 $completioncache = cache::make('core', 'completion');
1022 // Get user ID
1023 if (!$userid) {
1024 $userid = $USER->id;
1027 // See if requested data is present in cache (use cache for current user only).
1028 $usecache = $userid == $USER->id;
1029 $cacheddata = array();
1030 if ($usecache) {
1031 $key = $userid . '_' . $this->course->id;
1032 if (!isset($this->course->cacherev)) {
1033 $this->course = get_course($this->course_id);
1035 if ($cacheddata = $completioncache->get($key)) {
1036 if ($cacheddata['cacherev'] != $this->course->cacherev) {
1037 // Course structure has been changed since the last caching, forget the cache.
1038 $cacheddata = array();
1039 } else if (isset($cacheddata[$cm->id])) {
1040 return (object)$cacheddata[$cm->id];
1045 // Some call completion_info::get_data and pass $cm as an object with ID only. Make sure course is set as well.
1046 if ($cm instanceof stdClass && !isset($cm->course)) {
1047 $cm->course = $this->course_id;
1049 // Make sure we're working on a cm_info object.
1050 $cminfo = cm_info::create($cm, $userid);
1052 // Default data to return when no completion data is found.
1053 $defaultdata = [
1054 'id' => 0,
1055 'coursemoduleid' => $cminfo->id,
1056 'userid' => $userid,
1057 'completionstate' => 0,
1058 'viewed' => 0,
1059 'overrideby' => null,
1060 'timemodified' => 0,
1063 // If cached completion data is not found, fetch via SQL.
1064 // Fetch completion data for all of the activities in the course ONLY if we're caching the fetched completion data.
1065 // If we're not caching the completion data, then just fetch the completion data for the user in this course module.
1066 if ($usecache && $wholecourse) {
1067 // Get whole course data for cache.
1068 $alldatabycmc = $DB->get_records_sql("SELECT cm.id AS cmid, cmc.*
1069 FROM {course_modules} cm
1070 LEFT JOIN {course_modules_completion} cmc ON cmc.coursemoduleid = cm.id
1071 AND cmc.userid = ?
1072 INNER JOIN {modules} m ON m.id = cm.module
1073 WHERE m.visible = 1 AND cm.course = ?", [$userid, $this->course->id]);
1075 $cminfos = get_fast_modinfo($cm->course, $userid)->get_cms();
1077 // Reindex by course module id.
1078 foreach ($alldatabycmc as $data) {
1080 // Filter acitivites with no cm_info (missing plugins or other causes).
1081 if (!isset($cminfos[$data->cmid])) {
1082 continue;
1085 if (empty($data->coursemoduleid)) {
1086 $cacheddata[$data->cmid] = $defaultdata;
1087 $cacheddata[$data->cmid]['coursemoduleid'] = $data->cmid;
1088 } else {
1089 $cacheddata[$data->cmid] = (array) $data;
1092 // Add the other completion data for this user in this module instance.
1093 $othercminfo = $cminfos[$data->cmid];
1094 $cacheddata[$othercminfo->id] += $this->get_other_cm_completion_data($othercminfo, $userid);
1097 if (!isset($cacheddata[$cminfo->id])) {
1098 $errormessage = "Unexpected error: course-module {$cminfo->id} could not be found on course {$this->course->id}";
1099 $this->internal_systemerror($errormessage);
1102 } else {
1103 // Get single record
1104 $data = $DB->get_record('course_modules_completion', array('coursemoduleid' => $cminfo->id, 'userid' => $userid));
1105 if ($data) {
1106 $data = (array)$data;
1107 } else {
1108 // Row not present counts as 'not complete'.
1109 $data = $defaultdata;
1111 // Fill the other completion data for this user in this module instance.
1112 $data += $this->get_other_cm_completion_data($cminfo, $userid);
1114 // Put in cache
1115 $cacheddata[$cminfo->id] = $data;
1118 if ($usecache) {
1119 $cacheddata['cacherev'] = $this->course->cacherev;
1120 $completioncache->set($key, $cacheddata);
1122 return (object)$cacheddata[$cminfo->id];
1126 * Get the latest completion state for each criteria used in the module
1128 * @param cm_info $cm The corresponding module's information
1129 * @param int $userid The id for the user we are calculating core completion state
1130 * @return array $data The individualised core completion state used in the module.
1131 * Consists of the following keys completiongrade, passgrade, viewed
1133 public function get_core_completion_state(cm_info $cm, int $userid): array {
1134 global $DB;
1135 $data = [];
1136 // Include in the completion info the grade completion, if necessary.
1137 if (!is_null($cm->completiongradeitemnumber)) {
1138 $newstate = $this->get_grade_completion($cm, $userid);
1139 $data['completiongrade'] = $newstate;
1141 if ($cm->completionpassgrade) {
1142 // If we are asking to use pass grade completion but haven't set it properly,
1143 // then default to COMPLETION_COMPLETE_PASS.
1144 if ($newstate == COMPLETION_COMPLETE) {
1145 $newstate = COMPLETION_COMPLETE_PASS;
1148 // The activity is using 'passing grade' criteria therefore fail indication should be on this criteria.
1149 // The user has received a (failing) grade so 'completiongrade' should properly indicate this.
1150 if ($newstate == COMPLETION_COMPLETE_FAIL) {
1151 $data['completiongrade'] = COMPLETION_COMPLETE;
1154 $data['passgrade'] = $newstate;
1158 // If view is required, try and fetch from the db. In some cases, cache can be invalid.
1159 if ($cm->completionview == COMPLETION_VIEW_REQUIRED) {
1160 $data['viewed'] = COMPLETION_INCOMPLETE;
1161 $record = $DB->get_record('course_modules_completion', array('coursemoduleid' => $cm->id, 'userid' => $userid));
1162 if ($record) {
1163 $data['viewed'] = ($record->viewed == COMPLETION_VIEWED ? COMPLETION_COMPLETE : COMPLETION_INCOMPLETE);
1167 return $data;
1171 * Adds the user's custom completion data on the given course module.
1173 * @param cm_info $cm The course module information.
1174 * @param int $userid The user ID.
1175 * @return array The additional completion data.
1177 protected function get_other_cm_completion_data(cm_info $cm, int $userid): array {
1178 $data = $this->get_core_completion_state($cm, $userid);
1180 // Custom activity module completion data.
1182 // Cast custom data to array before checking for custom completion rules.
1183 // We call ->get_custom_data() instead of ->customdata here because there is the chance of recursive calling,
1184 // and we cannot call a getter from a getter in PHP.
1185 $customdata = (array) $cm->get_custom_data();
1186 // Return early if the plugin does not define custom completion rules.
1187 if (empty($customdata['customcompletionrules'])) {
1188 return $data;
1191 // Return early if the activity modules doe not implement the activity_custom_completion class.
1192 $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cm->modname);
1193 if (!$cmcompletionclass) {
1194 return $data;
1197 /** @var activity_custom_completion $customcmcompletion */
1198 $customcmcompletion = new $cmcompletionclass($cm, $userid, $data);
1199 foreach ($customdata['customcompletionrules'] as $rule => $enabled) {
1200 if (!$enabled) {
1201 // Skip inactive completion rules.
1202 continue;
1204 // Get this custom completion rule's completion state.
1205 $data['customcompletion'][$rule] = $customcmcompletion->get_state($rule);
1208 return $data;
1212 * Updates completion data for a particular coursemodule and user (user is
1213 * determined from $data).
1215 * (Internal function. Not private, so we can unit-test it.)
1217 * @param stdClass|cm_info $cm Activity
1218 * @param stdClass $data Data about completion for that user
1219 * @param bool $isbulkupdate If bulk grade update is happening.
1221 public function internal_set_data($cm, $data, $isbulkupdate = false) {
1222 global $USER, $DB, $CFG;
1223 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_activity.php');
1225 $transaction = $DB->start_delegated_transaction();
1226 if (!$data->id) {
1227 // Check there isn't really a row
1228 $data->id = $DB->get_field('course_modules_completion', 'id',
1229 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1231 if (!$data->id) {
1232 // Didn't exist before, needs creating
1233 $data->id = $DB->insert_record('course_modules_completion', $data);
1234 } else {
1235 // Has real (nonzero) id meaning that a database row exists, update
1236 $DB->update_record('course_modules_completion', $data);
1238 $transaction->allow_commit();
1240 $cmcontext = context_module::instance($data->coursemoduleid);
1242 $completioncache = cache::make('core', 'completion');
1243 if ($data->userid == $USER->id) {
1244 // Fetch other completion data to cache (e.g. require grade completion status, custom completion rule statues).
1245 $cminfo = cm_info::create($cm, $data->userid); // Make sure we're working on a cm_info object.
1246 $otherdata = $this->get_other_cm_completion_data($cminfo, $data->userid);
1247 foreach ($otherdata as $key => $value) {
1248 $data->$key = $value;
1251 // Update module completion in user's cache.
1252 if (!($cachedata = $completioncache->get($data->userid . '_' . $cm->course))
1253 || $cachedata['cacherev'] != $this->course->cacherev) {
1254 $cachedata = array('cacherev' => $this->course->cacherev);
1256 $cachedata[$cm->id] = $data;
1257 $completioncache->set($data->userid . '_' . $cm->course, $cachedata);
1259 // reset modinfo for user (no need to call rebuild_course_cache())
1260 get_fast_modinfo($cm->course, 0, true);
1261 } else {
1262 // Remove another user's completion cache for this course.
1263 $completioncache->delete($data->userid . '_' . $cm->course);
1266 // For single user actions the code must reevaluate some completion state instantly, see MDL-32103.
1267 if ($isbulkupdate) {
1268 return;
1269 } else {
1270 $userdata = ['userid' => $data->userid, 'courseid' => $this->course_id];
1271 $coursecompletionid = \core_completion\api::mark_course_completions_activity_criteria($userdata);
1272 if ($coursecompletionid) {
1273 aggregate_completions($coursecompletionid);
1277 // Trigger an event for course module completion changed.
1278 $event = \core\event\course_module_completion_updated::create(array(
1279 'objectid' => $data->id,
1280 'context' => $cmcontext,
1281 'relateduserid' => $data->userid,
1282 'other' => array(
1283 'relateduserid' => $data->userid,
1284 'overrideby' => $data->overrideby,
1285 'completionstate' => $data->completionstate
1288 $event->add_record_snapshot('course_modules_completion', $data);
1289 $event->trigger();
1293 * Return whether or not the course has activities with completion enabled.
1295 * @return boolean true when there is at least one activity with completion enabled.
1297 public function has_activities() {
1298 $modinfo = get_fast_modinfo($this->course);
1299 foreach ($modinfo->get_cms() as $cm) {
1300 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1301 return true;
1304 return false;
1308 * Obtains a list of activities for which completion is enabled on the
1309 * course. The list is ordered by the section order of those activities.
1311 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1312 * empty array if none
1314 public function get_activities() {
1315 $modinfo = get_fast_modinfo($this->course);
1316 $result = array();
1317 foreach ($modinfo->get_cms() as $cm) {
1318 if ($cm->completion != COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) {
1319 $result[$cm->id] = $cm;
1322 return $result;
1326 * Checks to see if the userid supplied has a tracked role in
1327 * this course
1329 * @param int $userid User id
1330 * @return bool
1332 public function is_tracked_user($userid) {
1333 return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1337 * Returns the number of users whose progress is tracked in this course.
1339 * Optionally supply a search's where clause, or a group id.
1341 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1342 * @param array $whereparams Where clause params
1343 * @param int $groupid Group id
1344 * @return int Number of tracked users
1346 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1347 global $DB;
1349 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1350 context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1351 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1352 if ($where) {
1353 $sql .= " WHERE $where";
1356 $params = array_merge($enrolledparams, $whereparams);
1357 return $DB->count_records_sql($sql, $params);
1361 * Return array of users whose progress is tracked in this course.
1363 * Optionally supply a search's where clause, group id, sorting, paging.
1365 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1366 * @param array $whereparams Where clause params (optional)
1367 * @param int $groupid Group ID to restrict to (optional)
1368 * @param string $sort Order by clause (optional)
1369 * @param int $limitfrom Result start (optional)
1370 * @param int $limitnum Result max size (optional)
1371 * @param context $extracontext If set, includes extra user information fields
1372 * as appropriate to display for current user in this context
1373 * @return array Array of user objects with user fields (including all identity fields)
1375 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1376 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1378 global $DB;
1380 list($enrolledsql, $params) = get_enrolled_sql(
1381 context_course::instance($this->course->id),
1382 'moodle/course:isincompletionreports', $groupid, true);
1384 $userfieldsapi = \core_user\fields::for_identity($extracontext)->with_name()->excluding('id', 'idnumber');
1385 $fieldssql = $userfieldsapi->get_sql('u', true);
1386 $sql = 'SELECT u.id, u.idnumber ' . $fieldssql->selects;
1387 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1388 $sql .= $fieldssql->joins;
1389 $params = array_merge($params, $fieldssql->params);
1391 if ($where) {
1392 $sql .= " AND $where";
1393 $params = array_merge($params, $whereparams);
1396 if ($sort) {
1397 $sql .= " ORDER BY $sort";
1400 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1404 * Obtains progress information across a course for all users on that course, or
1405 * for all users in a specific group. Intended for use when displaying progress.
1407 * This includes only users who, in course context, have one of the roles for
1408 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1410 * Users are included (in the first array) even if they do not have
1411 * completion progress for any course-module.
1413 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1414 * last name
1415 * @param string $where Where clause sql (optional)
1416 * @param array $where_params Where clause params (optional)
1417 * @param int $groupid Group ID or 0 (default)/false for all groups
1418 * @param int $pagesize Number of users to actually return (optional)
1419 * @param int $start User to start at if paging (optional)
1420 * @param context $extracontext If set, includes extra user information fields
1421 * as appropriate to display for current user in this context
1422 * @return stdClass with ->total and ->start (same as $start) and ->users;
1423 * an array of user objects (like mdl_user id, firstname, lastname)
1424 * containing an additional ->progress array of coursemoduleid => completionstate
1426 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1427 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1428 global $CFG, $DB;
1430 // Get list of applicable users
1431 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1432 $start, $pagesize, $extracontext);
1434 // Get progress information for these users in groups of 1, 000 (if needed)
1435 // to avoid making the SQL IN too long
1436 $results = array();
1437 $userids = array();
1438 foreach ($users as $user) {
1439 $userids[] = $user->id;
1440 $results[$user->id] = $user;
1441 $results[$user->id]->progress = array();
1444 for($i=0; $i<count($userids); $i+=1000) {
1445 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1447 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1448 array_splice($params, 0, 0, array($this->course->id));
1449 $rs = $DB->get_recordset_sql("
1450 SELECT
1451 cmc.*
1452 FROM
1453 {course_modules} cm
1454 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1455 WHERE
1456 cm.course=? AND cmc.userid $insql", $params);
1457 foreach ($rs as $progress) {
1458 $progress = (object)$progress;
1459 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1461 $rs->close();
1464 return $results;
1468 * Called by grade code to inform the completion system when a grade has
1469 * been changed. If the changed grade is used to determine completion for
1470 * the course-module, then the completion status will be updated.
1472 * @param stdClass|cm_info $cm Course-module for item that owns grade
1473 * @param grade_item $item Grade item
1474 * @param stdClass $grade
1475 * @param bool $deleted
1476 * @param bool $isbulkupdate If bulk grade update is happening.
1478 public function inform_grade_changed($cm, $item, $grade, $deleted, $isbulkupdate = false) {
1479 // Bail out now if completion is not enabled for course-module, it is enabled
1480 // but is set to manual, grade is not used to compute completion, or this
1481 // is a different numbered grade
1482 if (!$this->is_enabled($cm) ||
1483 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1484 is_null($cm->completiongradeitemnumber) ||
1485 $item->itemnumber != $cm->completiongradeitemnumber) {
1486 return;
1489 // What is the expected result based on this grade?
1490 if ($deleted) {
1491 // Grade being deleted, so only change could be to make it incomplete
1492 $possibleresult = COMPLETION_INCOMPLETE;
1493 } else {
1494 $possibleresult = self::internal_get_grade_state($item, $grade);
1497 // OK, let's update state based on this
1498 $this->update_state($cm, $possibleresult, $grade->userid, false, $isbulkupdate);
1502 * Calculates the completion state that would result from a graded item
1503 * (where grade-based completion is turned on) based on the actual grade
1504 * and settings.
1506 * Internal function. Not private, so we can unit-test it.
1508 * @param grade_item $item an instance of grade_item
1509 * @param grade_grade $grade an instance of grade_grade
1510 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1512 public static function internal_get_grade_state($item, $grade) {
1513 // If no grade is supplied or the grade doesn't have an actual value, then
1514 // this is not complete.
1515 if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1516 return COMPLETION_INCOMPLETE;
1519 // Conditions to show pass/fail:
1520 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1521 // b) Grade is visible (neither hidden nor hidden-until)
1522 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1523 // Use final grade if set otherwise raw grade
1524 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1526 // We are displaying and tracking pass/fail
1527 if ($score >= $item->gradepass) {
1528 return COMPLETION_COMPLETE_PASS;
1529 } else {
1530 return COMPLETION_COMPLETE_FAIL;
1532 } else {
1533 // Not displaying pass/fail, so just if there is a grade
1534 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1535 // Grade exists, so maybe complete now
1536 return COMPLETION_COMPLETE;
1537 } else {
1538 // Grade does not exist, so maybe incomplete now
1539 return COMPLETION_INCOMPLETE;
1545 * Aggregate activity completion state
1547 * @param int $type Aggregation type (COMPLETION_* constant)
1548 * @param bool $old Old state
1549 * @param bool $new New state
1550 * @return bool
1552 public static function aggregate_completion_states($type, $old, $new) {
1553 if ($type == COMPLETION_AND) {
1554 return $old && $new;
1555 } else {
1556 return $old || $new;
1561 * This is to be used only for system errors (things that shouldn't happen)
1562 * and not user-level errors.
1564 * @global type $CFG
1565 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1566 * @throws moodle_exception Exception with the error string as debug info
1568 public function internal_systemerror($error) {
1569 global $CFG;
1570 throw new moodle_exception('err_system','completion',
1571 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1576 * Aggregate criteria status's as per configured aggregation method.
1578 * @param int $method COMPLETION_AGGREGATION_* constant.
1579 * @param bool $data Criteria completion status.
1580 * @param bool|null $state Aggregation state.
1582 function completion_cron_aggregate($method, $data, &$state) {
1583 if ($method == COMPLETION_AGGREGATION_ALL) {
1584 if ($data && $state !== false) {
1585 $state = true;
1586 } else {
1587 $state = false;
1589 } else if ($method == COMPLETION_AGGREGATION_ANY) {
1590 if ($data) {
1591 $state = true;
1592 } else if (!$data && $state === null) {
1593 $state = false;
1599 * Aggregate courses completions. This function is called when activity completion status is updated
1600 * for single user. Also when regular completion task runs it aggregates completions for all courses and users.
1602 * @param int $coursecompletionid Course completion ID to update (if 0 - update for all courses and users)
1603 * @param bool $mtraceprogress To output debug info
1604 * @since Moodle 4.0
1606 function aggregate_completions(int $coursecompletionid, bool $mtraceprogress = false) {
1607 global $DB;
1609 if (!$coursecompletionid && $mtraceprogress) {
1610 mtrace('Aggregating completions');
1612 // Save time started.
1613 $timestarted = time();
1615 // Grab all criteria and their associated criteria completions.
1616 $sql = "SELECT DISTINCT c.id AS courseid, cr.id AS criteriaid, cco.userid, cr.criteriatype, ccocr.timecompleted
1617 FROM {course_completion_criteria} cr
1618 INNER JOIN {course} c ON cr.course = c.id
1619 INNER JOIN {course_completions} cco ON cco.course = c.id
1620 LEFT JOIN {course_completion_crit_compl} ccocr
1621 ON ccocr.criteriaid = cr.id AND cco.userid = ccocr.userid
1622 WHERE c.enablecompletion = 1
1623 AND cco.timecompleted IS NULL
1624 AND cco.reaggregate > 0";
1626 if ($coursecompletionid) {
1627 $sql .= " AND cco.id = ?";
1628 $param = $coursecompletionid;
1629 } else {
1630 $sql .= " AND cco.reaggregate < ? ORDER BY courseid, cco.userid";
1631 $param = $timestarted;
1633 $rs = $DB->get_recordset_sql($sql, [$param]);
1635 // Check if result is empty.
1636 if (!$rs->valid()) {
1637 $rs->close();
1638 return;
1641 $currentuser = null;
1642 $currentcourse = null;
1643 $completions = [];
1644 while (1) {
1645 // Grab records for current user/course.
1646 foreach ($rs as $record) {
1647 // If we are still grabbing the same users completions.
1648 if ($record->userid === $currentuser && $record->courseid === $currentcourse) {
1649 $completions[$record->criteriaid] = $record;
1650 } else {
1651 break;
1655 // Aggregate.
1656 if (!empty($completions)) {
1657 if (!$coursecompletionid && $mtraceprogress) {
1658 mtrace('Aggregating completions for user ' . $currentuser . ' in course ' . $currentcourse);
1661 // Get course info object.
1662 $info = new \completion_info((object)['id' => $currentcourse]);
1664 // Setup aggregation.
1665 $overall = $info->get_aggregation_method();
1666 $activity = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ACTIVITY);
1667 $prerequisite = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_COURSE);
1668 $role = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ROLE);
1670 $overallstatus = null;
1671 $activitystatus = null;
1672 $prerequisitestatus = null;
1673 $rolestatus = null;
1675 // Get latest timecompleted.
1676 $timecompleted = null;
1678 // Check each of the criteria.
1679 foreach ($completions as $params) {
1680 $timecompleted = max($timecompleted, $params->timecompleted);
1681 $completion = new \completion_criteria_completion((array)$params, false);
1683 // Handle aggregation special cases.
1684 if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) {
1685 completion_cron_aggregate($activity, $completion->is_complete(), $activitystatus);
1686 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) {
1687 completion_cron_aggregate($prerequisite, $completion->is_complete(), $prerequisitestatus);
1688 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ROLE) {
1689 completion_cron_aggregate($role, $completion->is_complete(), $rolestatus);
1690 } else {
1691 completion_cron_aggregate($overall, $completion->is_complete(), $overallstatus);
1695 // Include role criteria aggregation in overall aggregation.
1696 if ($rolestatus !== null) {
1697 completion_cron_aggregate($overall, $rolestatus, $overallstatus);
1700 // Include activity criteria aggregation in overall aggregation.
1701 if ($activitystatus !== null) {
1702 completion_cron_aggregate($overall, $activitystatus, $overallstatus);
1705 // Include prerequisite criteria aggregation in overall aggregation.
1706 if ($prerequisitestatus !== null) {
1707 completion_cron_aggregate($overall, $prerequisitestatus, $overallstatus);
1710 // If aggregation status is true, mark course complete for user.
1711 if ($overallstatus) {
1712 if (!$coursecompletionid && $mtraceprogress) {
1713 mtrace('Marking complete');
1716 $ccompletion = new \completion_completion([
1717 'course' => $params->courseid,
1718 'userid' => $params->userid
1720 $ccompletion->mark_complete($timecompleted);
1724 // If this is the end of the recordset, break the loop.
1725 if (!$rs->valid()) {
1726 $rs->close();
1727 break;
1730 // New/next user, update user details, reset completions.
1731 $currentuser = $record->userid;
1732 $currentcourse = $record->courseid;
1733 $completions = [];
1734 $completions[$record->criteriaid] = $record;
1737 // Mark all users as aggregated.
1738 if ($coursecompletionid) {
1739 $select = "reaggregate > 0 AND id = ?";
1740 $param = $coursecompletionid;
1741 } else {
1742 $select = "reaggregate > 0 AND reaggregate < ?";
1743 $param = $timestarted;
1744 if (PHPUNIT_TEST) {
1745 // MDL-33320: for instant completions we need aggregate to work in a single run.
1746 $DB->set_field('course_completions', 'reaggregate', $timestarted - 2);
1749 $DB->set_field_select('course_completions', 'reaggregate', 0, $select, [$param]);