Merge branch 'MDL-80233-main' of https://github.com/aanabit/moodle
[moodle.git] / lib / completionlib.php
blob59fdb3a9dc931624156eb365816497e9b682f18a
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;
30 use core_courseformat\base as course_format;
32 defined('MOODLE_INTERNAL') || die();
34 /**
35 * Include the required completion libraries
37 require_once $CFG->dirroot.'/completion/completion_aggregation.php';
38 require_once $CFG->dirroot.'/completion/criteria/completion_criteria.php';
39 require_once $CFG->dirroot.'/completion/completion_completion.php';
40 require_once $CFG->dirroot.'/completion/completion_criteria_completion.php';
43 /**
44 * The completion system is enabled in this site/course
46 define('COMPLETION_ENABLED', 1);
47 /**
48 * The completion system is not enabled in this site/course
50 define('COMPLETION_DISABLED', 0);
52 /**
53 * Completion tracking is disabled for this activity
54 * This is a completion tracking option per-activity (course_modules/completion)
56 define('COMPLETION_TRACKING_NONE', 0);
58 /**
59 * Manual completion tracking (user ticks box) is enabled for this activity
60 * This is a completion tracking option per-activity (course_modules/completion)
62 define('COMPLETION_TRACKING_MANUAL', 1);
63 /**
64 * Automatic completion tracking (system ticks box) is enabled for this activity
65 * This is a completion tracking option per-activity (course_modules/completion)
67 define('COMPLETION_TRACKING_AUTOMATIC', 2);
69 /**
70 * The user has not completed this activity.
71 * This is a completion state value (course_modules_completion/completionstate)
73 define('COMPLETION_INCOMPLETE', 0);
74 /**
75 * The user has completed this activity. It is not specified whether they have
76 * passed or failed it.
77 * This is a completion state value (course_modules_completion/completionstate)
79 define('COMPLETION_COMPLETE', 1);
80 /**
81 * The user has completed this activity with a grade above the pass mark.
82 * This is a completion state value (course_modules_completion/completionstate)
84 define('COMPLETION_COMPLETE_PASS', 2);
85 /**
86 * The user has completed this activity but their grade is less than the pass mark
87 * This is a completion state value (course_modules_completion/completionstate)
89 define('COMPLETION_COMPLETE_FAIL', 3);
91 /**
92 * Indicates that the user has received a failing grade for a hidden grade item.
94 define('COMPLETION_COMPLETE_FAIL_HIDDEN', 4);
96 /**
97 * The effect of this change to completion status is unknown.
98 * A completion effect changes (used only in update_state)
100 define('COMPLETION_UNKNOWN', -1);
102 * The user's grade has changed, so their new state might be
103 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
104 * A completion effect changes (used only in update_state)
106 define('COMPLETION_GRADECHANGE', -2);
109 * User must view this activity.
110 * Whether view is required to create an activity (course_modules/completionview)
112 define('COMPLETION_VIEW_REQUIRED', 1);
114 * User does not need to view this activity
115 * Whether view is required to create an activity (course_modules/completionview)
117 define('COMPLETION_VIEW_NOT_REQUIRED', 0);
120 * User has viewed this activity.
121 * Completion viewed state (course_modules_completion/viewed)
123 define('COMPLETION_VIEWED', 1);
125 * User has not viewed this activity.
126 * Completion viewed state (course_modules_completion/viewed)
128 define('COMPLETION_NOT_VIEWED', 0);
131 * Completion details should be ORed together and you should return false if
132 * none apply.
134 define('COMPLETION_OR', false);
136 * Completion details should be ANDed together and you should return true if
137 * none apply
139 define('COMPLETION_AND', true);
142 * Course completion criteria aggregation method.
144 define('COMPLETION_AGGREGATION_ALL', 1);
146 * Course completion criteria aggregation method.
148 define('COMPLETION_AGGREGATION_ANY', 2);
151 * Completion conditions will be displayed to user.
153 define('COMPLETION_SHOW_CONDITIONS', 1);
156 * Completion conditions will be hidden from user.
158 define('COMPLETION_HIDE_CONDITIONS', 0);
161 * Utility function for checking if the logged in user can view
162 * another's completion data for a particular course
164 * @access public
165 * @param int $userid Completion data's owner
166 * @param mixed $course Course object or Course ID (optional)
167 * @return boolean
169 function completion_can_view_data($userid, $course = null) {
170 global $USER;
172 if (!isloggedin()) {
173 return false;
176 if (!is_object($course)) {
177 $cid = $course;
178 $course = new stdClass();
179 $course->id = $cid;
182 // Check if this is the site course
183 if ($course->id == SITEID) {
184 $course = null;
187 // Check if completion is enabled
188 if ($course) {
189 $cinfo = new completion_info($course);
190 if (!$cinfo->is_enabled()) {
191 return false;
193 } else {
194 if (!completion_info::is_enabled_for_site()) {
195 return false;
199 // Is own user's data?
200 if ($USER->id == $userid) {
201 return true;
204 // Check capabilities
205 $personalcontext = context_user::instance($userid);
207 if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
208 return true;
209 } elseif (has_capability('report/completion:view', $personalcontext)) {
210 return true;
213 if ($course->id) {
214 $coursecontext = context_course::instance($course->id);
215 } else {
216 $coursecontext = context_system::instance();
219 if (has_capability('report/completion:view', $coursecontext)) {
220 return true;
223 return false;
228 * Class represents completion information for a course.
230 * Does not contain any data, so you can safely construct it multiple times
231 * without causing any problems.
233 * @package core
234 * @category completion
235 * @copyright 2008 Sam Marshall
236 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
238 class completion_info {
240 /* @var stdClass Course object passed during construction */
241 private $course;
243 /* @var int Course id */
244 public $course_id;
246 /* @var array Completion criteria {@link completion_info::get_criteria()} */
247 private $criteria;
250 * Return array of aggregation methods
251 * @return array
253 public static function get_aggregation_methods() {
254 return array(
255 COMPLETION_AGGREGATION_ALL => get_string('all'),
256 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
261 * Constructs with course details.
263 * When instantiating a new completion info object you must provide a course
264 * object with at least id, and enablecompletion properties. Property
265 * cacherev is needed if you check completion of the current user since
266 * it is used for cache validation.
268 * @param stdClass $course Moodle course object.
270 public function __construct($course) {
271 $this->course = $course;
272 $this->course_id = $course->id;
276 * Determines whether completion is enabled across entire site.
278 * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
279 * COMPLETION_DISABLED (false) if it's complete
281 public static function is_enabled_for_site() {
282 global $CFG;
283 return !empty($CFG->enablecompletion);
287 * Checks whether completion is enabled in a particular course and possibly
288 * activity.
290 * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
291 * completion enable state.
292 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
293 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
294 * for a course-module.
296 public function is_enabled($cm = null) {
297 global $CFG, $DB;
299 // First check global completion
300 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
301 return COMPLETION_DISABLED;
304 // Load data if we do not have enough
305 if (!isset($this->course->enablecompletion)) {
306 $this->course = get_course($this->course_id);
309 // Check course completion
310 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
311 return COMPLETION_DISABLED;
314 // If there was no $cm and we got this far, then it's enabled
315 if (!$cm) {
316 return COMPLETION_ENABLED;
319 // Return course-module completion value
320 return $cm->completion;
324 * Displays the 'Your progress' help icon, if completion tracking is enabled.
325 * Just prints the result of display_help_icon().
327 * @deprecated since Moodle 2.0 - Use display_help_icon instead.
329 public function print_help_icon() {
330 debugging('The function print_help_icon() is deprecated, please do not use it anymore.',
331 DEBUG_DEVELOPER);
332 print $this->display_help_icon();
336 * Returns the 'Your progress' help icon, if completion tracking is enabled.
338 * @return string HTML code for help icon, or blank if not needed
339 * @deprecated since Moodle 4.0 - The 'Your progress' info isn't displayed any more.
341 public function display_help_icon() {
342 global $PAGE, $OUTPUT, $USER;
343 debugging('The function display_help_icon() is deprecated, please do not use it anymore.',
344 DEBUG_DEVELOPER);
345 $result = '';
346 if ($this->is_enabled() && !$PAGE->user_is_editing() && $this->is_tracked_user($USER->id) && isloggedin() &&
347 !isguestuser()) {
348 $result .= html_writer::tag('div', get_string('yourprogress','completion') .
349 $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
350 'class' => 'completionprogress'));
352 return $result;
356 * Get a course completion for a user
358 * @param int $user_id User id
359 * @param int $criteriatype Specific criteria type to return
360 * @return bool|completion_criteria_completion returns false on fail
362 public function get_completion($user_id, $criteriatype) {
363 $completions = $this->get_completions($user_id, $criteriatype);
365 if (empty($completions)) {
366 return false;
367 } elseif (count($completions) > 1) {
368 throw new \moodle_exception('multipleselfcompletioncriteria', 'completion');
371 return $completions[0];
375 * Get all course criteria's completion objects for a user
377 * @param int $user_id User id
378 * @param int $criteriatype Specific criteria type to return (optional)
379 * @return array
381 public function get_completions($user_id, $criteriatype = null) {
382 $criteria = $this->get_criteria($criteriatype);
384 $completions = array();
386 foreach ($criteria as $criterion) {
387 $params = array(
388 'course' => $this->course_id,
389 'userid' => $user_id,
390 'criteriaid' => $criterion->id
393 $completion = new completion_criteria_completion($params);
394 $completion->attach_criteria($criterion);
396 $completions[] = $completion;
399 return $completions;
403 * Get completion object for a user and a criteria
405 * @param int $user_id User id
406 * @param completion_criteria $criteria Criteria object
407 * @return completion_criteria_completion
409 public function get_user_completion($user_id, $criteria) {
410 $params = array(
411 'course' => $this->course_id,
412 'userid' => $user_id,
413 'criteriaid' => $criteria->id,
416 $completion = new completion_criteria_completion($params);
417 return $completion;
421 * Check if course has completion criteria set
423 * @return bool Returns true if there are criteria
425 public function has_criteria() {
426 $criteria = $this->get_criteria();
428 return (bool) count($criteria);
432 * Get course completion criteria
434 * @param int $criteriatype Specific criteria type to return (optional)
436 public function get_criteria($criteriatype = null) {
438 // Fill cache if empty
439 if (!is_array($this->criteria)) {
440 global $DB;
442 $params = array(
443 'course' => $this->course->id
446 // Load criteria from database
447 $records = (array)$DB->get_records('course_completion_criteria', $params);
449 // Order records so activities are in the same order as they appear on the course view page.
450 if ($records) {
451 $activitiesorder = array_keys(get_fast_modinfo($this->course)->get_cms());
452 usort($records, function ($a, $b) use ($activitiesorder) {
453 $aidx = ($a->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
454 array_search($a->moduleinstance, $activitiesorder) : false;
455 $bidx = ($b->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
456 array_search($b->moduleinstance, $activitiesorder) : false;
457 if ($aidx === false || $bidx === false || $aidx == $bidx) {
458 return 0;
460 return ($aidx < $bidx) ? -1 : 1;
464 // Build array of criteria objects
465 $this->criteria = array();
466 foreach ($records as $record) {
467 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
471 // If after all criteria
472 if ($criteriatype === null) {
473 return $this->criteria;
476 // If we are only after a specific criteria type
477 $criteria = array();
478 foreach ($this->criteria as $criterion) {
480 if ($criterion->criteriatype != $criteriatype) {
481 continue;
484 $criteria[$criterion->id] = $criterion;
487 return $criteria;
491 * Get aggregation method
493 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
494 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
496 public function get_aggregation_method($criteriatype = null) {
497 $params = array(
498 'course' => $this->course_id,
499 'criteriatype' => $criteriatype
502 $aggregation = new completion_aggregation($params);
504 if (!$aggregation->id) {
505 $aggregation->method = COMPLETION_AGGREGATION_ALL;
508 return $aggregation->method;
512 * @deprecated since Moodle 2.8 MDL-46290.
514 public function get_incomplete_criteria() {
515 throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
519 * Clear old course completion criteria
521 public function clear_criteria() {
522 global $DB;
524 // Remove completion criteria records for the course itself, and any records that refer to the course.
525 $select = 'course = :course OR (criteriatype = :type AND courseinstance = :courseinstance)';
526 $params = [
527 'course' => $this->course_id,
528 'type' => COMPLETION_CRITERIA_TYPE_COURSE,
529 'courseinstance' => $this->course_id,
532 $DB->delete_records_select('course_completion_criteria', $select, $params);
533 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
535 $this->delete_course_completion_data();
539 * Has the supplied user completed this course
541 * @param int $user_id User's id
542 * @return boolean
544 public function is_course_complete($user_id) {
545 $params = array(
546 'userid' => $user_id,
547 'course' => $this->course_id
550 $ccompletion = new completion_completion($params);
551 return $ccompletion->is_complete();
555 * Check whether the supplied user can override the activity completion statuses within the current course.
557 * @param stdClass $user The user object.
558 * @return bool True if the user can override, false otherwise.
560 public function user_can_override_completion($user) {
561 return has_capability('moodle/course:overridecompletion', context_course::instance($this->course_id), $user);
565 * Updates (if necessary) the completion state of activity $cm for the given
566 * user.
568 * For manual completion, this function is called when completion is toggled
569 * with $possibleresult set to the target state.
571 * For automatic completion, this function should be called every time a module
572 * does something which might influence a user's completion state. For example,
573 * if a forum provides options for marking itself 'completed' once a user makes
574 * N posts, this function should be called every time a user makes a new post.
575 * [After the post has been saved to the database]. When calling, you do not
576 * need to pass in the new completion state. Instead this function carries out completion
577 * calculation by checking grades and viewed state itself, and calling the involved module
578 * via mod_{modulename}\\completion\\custom_completion::get_overall_completion_state() to
579 * check module-specific conditions.
581 * @param stdClass|cm_info $cm Course-module
582 * @param int $possibleresult Expected completion result. If the event that
583 * has just occurred (e.g. add post) can only result in making the activity
584 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
585 * has just occurred (e.g. delete post) can only result in making the activity
586 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
587 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
588 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
589 * processing early if the user's completion state already matches the expected
590 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
591 * must be used; these directly set the specified state.
592 * @param int $userid User ID to be updated. Default 0 = current user
593 * @param bool $override Whether manually overriding the existing completion state.
594 * @param bool $isbulkupdate If bulk grade update is happening.
595 * @return void
596 * @throws moodle_exception if trying to override without permission.
598 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0,
599 $override = false, $isbulkupdate = false) {
600 global $USER;
602 // Do nothing if completion is not enabled for that activity
603 if (!$this->is_enabled($cm)) {
604 return;
607 // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
608 if ($override) {
609 if (!$this->user_can_override_completion($USER)) {
610 throw new required_capability_exception(context_course::instance($this->course_id),
611 'moodle/course:overridecompletion', 'nopermission', '');
615 // Default to current user if one is not provided.
616 if ($userid == 0) {
617 $userid = $USER->id;
620 // Delete the cm's cached completion data for this user if automatic completion is enabled.
621 // This ensures any changes to the status of individual completion conditions in the activity will be fetched.
622 if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC) {
623 $completioncache = cache::make('core', 'completion');
624 $completionkey = $userid . '_' . $this->course->id;
625 $completiondata = $completioncache->get($completionkey);
627 if ($completiondata !== false) {
628 unset($completiondata[$cm->id]);
629 $completioncache->set($completionkey, $completiondata);
633 // Get current value of completion state and do nothing if it's same as
634 // the possible result of this change. If the change is to COMPLETE and the
635 // current value is one of the COMPLETE_xx subtypes, ignore that as well
636 $current = $this->get_data($cm, false, $userid);
637 if ($possibleresult == $current->completionstate ||
638 ($possibleresult == COMPLETION_COMPLETE &&
639 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
640 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
641 return;
644 // The activity completion alters the course state cache for this particular user.
645 $course = get_course($cm->course);
646 if ($course) {
647 course_format::session_cache_reset($course);
650 // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
651 // unless processing another override.
652 // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
653 // overridden to INCOMPLETE to still be processed by normal completion triggers.
654 if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC && !is_null($current->overrideby)
655 && $current->completionstate == COMPLETION_COMPLETE && !$override) {
656 return;
659 // For manual tracking, or if overriding the completion state, we set the state directly.
660 if ($cm->completion == COMPLETION_TRACKING_MANUAL || $override) {
661 switch($possibleresult) {
662 case COMPLETION_COMPLETE:
663 case COMPLETION_INCOMPLETE:
664 $newstate = $possibleresult;
665 break;
666 default:
667 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
670 } else {
671 $newstate = $this->internal_get_state($cm, $userid, $current);
674 // If the overall completion state has changed, update it in the cache.
675 if ($newstate != $current->completionstate) {
676 $current->completionstate = $newstate;
677 $current->timemodified = time();
678 $current->overrideby = $override ? $USER->id : null;
679 $this->internal_set_data($cm, $current, $isbulkupdate);
684 * Calculates the completion state for an activity and user.
686 * Internal function. Not private, so we can unit-test it.
688 * @param stdClass|cm_info $cm Activity
689 * @param int $userid ID of user
690 * @param stdClass $current Previous completion information from database
691 * @return mixed
693 public function internal_get_state($cm, $userid, $current) {
694 global $USER, $DB;
696 // Get user ID
697 if (!$userid) {
698 $userid = $USER->id;
701 $newstate = COMPLETION_COMPLETE;
702 if ($cm instanceof stdClass) {
703 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it.
704 if (!isset($cm->modname)) {
705 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
707 // Some functions call this method and pass $cm as an object with ID only. Make sure course is set as well.
708 if (!isset($cm->course)) {
709 $cm->course = $this->course_id;
712 // Make sure we're using a cm_info object.
713 $cminfo = cm_info::create($cm, $userid);
714 $completionstate = $this->get_core_completion_state($cminfo, $userid);
716 if (plugin_supports('mod', $cminfo->modname, FEATURE_COMPLETION_HAS_RULES)) {
717 $response = true;
718 $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cminfo->modname);
719 if ($cmcompletionclass) {
720 /** @var activity_custom_completion $cmcompletion */
721 $cmcompletion = new $cmcompletionclass($cminfo, $userid, $completionstate);
722 $response = $cmcompletion->get_overall_completion_state() != COMPLETION_INCOMPLETE;
725 if (!$response) {
726 return COMPLETION_INCOMPLETE;
730 if ($completionstate) {
731 // We have allowed the plugins to do it's thing and run their own checks.
732 // We have now reached a state where we need to AND all the calculated results.
733 // Preference for COMPLETION_COMPLETE_PASS over COMPLETION_COMPLETE for proper indication in reports.
734 $newstate = array_reduce($completionstate, function($carry, $value) {
735 if (in_array(COMPLETION_INCOMPLETE, [$carry, $value])) {
736 return COMPLETION_INCOMPLETE;
737 } else if (in_array(COMPLETION_COMPLETE_FAIL, [$carry, $value])) {
738 return COMPLETION_COMPLETE_FAIL;
739 } else {
740 return in_array(COMPLETION_COMPLETE_PASS, [$carry, $value]) ? COMPLETION_COMPLETE_PASS : $value;
743 }, COMPLETION_COMPLETE);
746 return $newstate;
751 * Fetches the completion state for an activity completion's require grade completion requirement.
753 * @param cm_info $cm The course module information.
754 * @param int $userid The user ID.
755 * @return int The completion state.
757 public function get_grade_completion(cm_info $cm, int $userid): int {
758 global $CFG;
760 require_once($CFG->libdir . '/gradelib.php');
761 $item = grade_item::fetch([
762 'courseid' => $cm->course,
763 'itemtype' => 'mod',
764 'itemmodule' => $cm->modname,
765 'iteminstance' => $cm->instance,
766 'itemnumber' => $cm->completiongradeitemnumber
768 if ($item) {
769 // Fetch 'grades' (will be one or none).
770 $grades = grade_grade::fetch_users_grades($item, [$userid], false);
771 if (empty($grades)) {
772 // No grade for user.
773 return COMPLETION_INCOMPLETE;
775 if (count($grades) > 1) {
776 $this->internal_systemerror("Unexpected result: multiple grades for
777 item '{$item->id}', user '{$userid}'");
779 $returnpassfail = !empty($cm->completionpassgrade);
780 return self::internal_get_grade_state($item, reset($grades), $returnpassfail);
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));
918 $DB->delete_records_select('course_modules_viewed',
919 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
920 [$this->course_id]);
921 // Wipe course completion data too.
922 $this->delete_course_completion_data();
926 * Deletes completion state related to an activity for all users.
928 * Intended for use only when the activity itself is deleted.
930 * @param stdClass|cm_info $cm Activity
932 public function delete_all_state($cm) {
933 global $DB;
935 // Delete from database
936 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
938 // Check if there is an associated course completion criteria
939 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
940 $acriteria = false;
941 foreach ($criteria as $criterion) {
942 if ($criterion->moduleinstance == $cm->id) {
943 $acriteria = $criterion;
944 break;
948 if ($acriteria) {
949 // Delete all criteria completions relating to this activity
950 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
951 $DB->delete_records('course_completions', array('course' => $this->course_id));
954 // Difficult to find affected users, just purge all completion cache.
955 cache::make('core', 'completion')->purge();
956 cache::make('core', 'coursecompletion')->purge();
960 * Recalculates completion state related to an activity for all users.
962 * Intended for use if completion conditions change. (This should be avoided
963 * as it may cause some things to become incomplete when they were previously
964 * complete, with the effect - for example - of hiding a later activity that
965 * was previously available.)
967 * Resetting state of manual tickbox has same result as deleting state for
968 * it.
970 * @param stcClass|cm_info $cm Activity
972 public function reset_all_state($cm) {
973 global $DB;
975 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
976 $this->delete_all_state($cm);
977 return;
979 // Get current list of users with completion state
980 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
981 $keepusers = array();
982 foreach ($rs as $rec) {
983 $keepusers[] = $rec->userid;
985 $rs->close();
987 // Delete all existing state.
988 $this->delete_all_state($cm);
990 // Merge this with list of planned users (according to roles)
991 $trackedusers = $this->get_tracked_users();
992 foreach ($trackedusers as $trackeduser) {
993 $keepusers[] = $trackeduser->id;
995 $keepusers = array_unique($keepusers);
997 // Recalculate state for each kept user
998 foreach ($keepusers as $keepuser) {
999 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
1004 * Obtains completion data for a particular activity and user (from the
1005 * completion cache if available, or by SQL query)
1007 * @param stdClass|cm_info $cm Activity; only required field is ->id
1008 * @param bool $wholecourse If true (default false) then, when necessary to
1009 * fill the cache, retrieves information from the entire course not just for
1010 * this one activity
1011 * @param int $userid User ID or 0 (default) for current user
1012 * @param null $unused This parameter has been deprecated since 4.0 and should not be used anymore.
1013 * @return object Completion data. Record from course_modules_completion plus other completion statuses such as
1014 * - Completion status for 'must-receive-grade' completion rule.
1015 * - Custom completion statuses defined by the activity module plugin.
1017 public function get_data($cm, $wholecourse = false, $userid = 0, $unused = null) {
1018 global $USER, $DB;
1020 if ($unused !== null) {
1021 debugging('Deprecated argument passed to ' . __FUNCTION__, DEBUG_DEVELOPER);
1024 $completioncache = cache::make('core', 'completion');
1026 // Get user ID
1027 if (!$userid) {
1028 $userid = $USER->id;
1031 // Some call completion_info::get_data and pass $cm as an object with ID only. Make sure course is set as well.
1032 if ($cm instanceof stdClass && !isset($cm->course)) {
1033 $cm->course = $this->course_id;
1035 // Make sure we're working on a cm_info object.
1036 $cminfo = cm_info::create($cm, $userid);
1038 // Create an anonymous function to remove the 'other_cm_completion_data_fetched' key.
1039 $returnfilteredvalue = function(array $value): stdClass {
1040 return (object) array_filter($value, function(string $key): bool {
1041 return $key !== 'other_cm_completion_data_fetched';
1042 }, ARRAY_FILTER_USE_KEY);
1045 // See if requested data is present in cache (use cache for current user only).
1046 $usecache = $userid == $USER->id;
1047 $cacheddata = array();
1048 if ($usecache) {
1049 $key = $userid . '_' . $this->course->id;
1050 if (!isset($this->course->cacherev)) {
1051 $this->course = get_course($this->course_id);
1053 if ($cacheddata = ($completioncache->get($key) ?: [])) {
1054 if ($cacheddata['cacherev'] != $this->course->cacherev) {
1055 // Course structure has been changed since the last caching, forget the cache.
1056 $cacheddata = array();
1057 } else if (isset($cacheddata[$cminfo->id])) {
1058 $data = (array) $cacheddata[$cminfo->id];
1059 if (empty($data['other_cm_completion_data_fetched'])) {
1060 $data += $this->get_other_cm_completion_data($cminfo, $userid);
1061 $data['other_cm_completion_data_fetched'] = true;
1063 // Put in cache.
1064 $cacheddata[$cminfo->id] = $data;
1065 $completioncache->set($key, $cacheddata);
1068 return $returnfilteredvalue($cacheddata[$cminfo->id]);
1073 // Default data to return when no completion data is found.
1074 $defaultdata = [
1075 'id' => 0,
1076 'coursemoduleid' => $cminfo->id,
1077 'userid' => $userid,
1078 'completionstate' => 0,
1079 'viewed' => 0,
1080 'overrideby' => null,
1081 'timemodified' => 0,
1084 // If cached completion data is not found, fetch via SQL.
1085 // Fetch completion data for all of the activities in the course ONLY if we're caching the fetched completion data.
1086 // If we're not caching the completion data, then just fetch the completion data for the user in this course module.
1087 if ($usecache && $wholecourse) {
1088 // Get whole course data for cache.
1089 $alldatabycmc = $DB->get_records_sql("SELECT cm.id AS cmid, cmc.*,
1090 CASE WHEN cmv.id IS NULL THEN 0 ELSE 1 END AS viewed
1091 FROM {course_modules} cm
1092 LEFT JOIN {course_modules_completion} cmc
1093 ON cmc.coursemoduleid = cm.id AND cmc.userid = ?
1094 LEFT JOIN {course_modules_viewed} cmv
1095 ON cmv.coursemoduleid = cm.id AND cmv.userid = ?
1096 INNER JOIN {modules} m ON m.id = cm.module
1097 WHERE m.visible = 1 AND cm.course = ?",
1098 [$userid, $userid, $this->course->id]);
1099 $cminfos = get_fast_modinfo($cm->course, $userid)->get_cms();
1101 // Reindex by course module id.
1102 foreach ($alldatabycmc as $data) {
1104 // Filter acitivites with no cm_info (missing plugins or other causes).
1105 if (!isset($cminfos[$data->cmid])) {
1106 continue;
1109 if (empty($data->coursemoduleid)) {
1110 $cacheddata[$data->cmid] = $defaultdata;
1111 if ($data->viewed) {
1112 $cacheddata[$data->cmid]['viewed'] = $data->viewed;
1114 $cacheddata[$data->cmid]['coursemoduleid'] = $data->cmid;
1115 } else {
1116 unset($data->cmid);
1117 $cacheddata[$data->coursemoduleid] = (array) $data;
1121 if (!isset($cacheddata[$cminfo->id])) {
1122 $errormessage = "Unexpected error: course-module {$cminfo->id} could not be found on course {$this->course->id}";
1123 $this->internal_systemerror($errormessage);
1126 $data = $cacheddata[$cminfo->id];
1127 } else {
1128 // Get single record
1129 $data = $this->get_completion_data($cminfo->id, $userid, $defaultdata);
1130 // Put in cache.
1131 $cacheddata[$cminfo->id] = $data;
1134 // Fill the other completion data for this user in this module instance.
1135 $data += $this->get_other_cm_completion_data($cminfo, $userid);
1136 $data['other_cm_completion_data_fetched'] = true;
1138 // Put in cache
1139 $cacheddata[$cminfo->id] = $data;
1141 if ($usecache) {
1142 $cacheddata['cacherev'] = $this->course->cacherev;
1143 $completioncache->set($key, $cacheddata);
1146 return $returnfilteredvalue($cacheddata[$cminfo->id]);
1150 * Get the latest completion state for each criteria used in the module
1152 * @param cm_info $cm The corresponding module's information
1153 * @param int $userid The id for the user we are calculating core completion state
1154 * @return array $data The individualised core completion state used in the module.
1155 * Consists of the following keys completiongrade, passgrade, viewed
1157 public function get_core_completion_state(cm_info $cm, int $userid): array {
1158 global $DB;
1159 $data = [];
1160 // Include in the completion info the grade completion, if necessary.
1161 if (!is_null($cm->completiongradeitemnumber)) {
1162 $newstate = $this->get_grade_completion($cm, $userid);
1163 $data['completiongrade'] = $newstate;
1165 if ($cm->completionpassgrade) {
1166 // If we are asking to use pass grade completion but haven't set it properly,
1167 // then default to COMPLETION_COMPLETE_PASS.
1168 if ($newstate == COMPLETION_COMPLETE) {
1169 $newstate = COMPLETION_COMPLETE_PASS;
1172 // No need to show failing status for the completiongrade condition when passing grade condition is set.
1173 if (in_array($newstate, [COMPLETION_COMPLETE_FAIL, COMPLETION_COMPLETE_FAIL_HIDDEN])) {
1174 $data['completiongrade'] = COMPLETION_COMPLETE;
1176 // If the grade received by the user is a failing grade for a hidden grade item,
1177 // the 'Require passing grade' criterion is considered incomplete.
1178 if ($newstate == COMPLETION_COMPLETE_FAIL_HIDDEN) {
1179 $newstate = COMPLETION_INCOMPLETE;
1182 $data['passgrade'] = $newstate;
1186 // If view is required, try and fetch from the db. In some cases, cache can be invalid.
1187 if ($cm->completionview == COMPLETION_VIEW_REQUIRED) {
1188 $data['viewed'] = COMPLETION_INCOMPLETE;
1189 $record = $DB->record_exists('course_modules_viewed', ['coursemoduleid' => $cm->id, 'userid' => $userid]);
1190 $data['viewed'] = $record ? COMPLETION_COMPLETE : COMPLETION_INCOMPLETE;
1193 return $data;
1197 * Adds the user's custom completion data on the given course module.
1199 * @param cm_info $cm The course module information.
1200 * @param int $userid The user ID.
1201 * @return array The additional completion data.
1203 protected function get_other_cm_completion_data(cm_info $cm, int $userid): array {
1204 $data = $this->get_core_completion_state($cm, $userid);
1206 // Custom activity module completion data.
1208 // Cast custom data to array before checking for custom completion rules.
1209 // We call ->get_custom_data() instead of ->customdata here because there is the chance of recursive calling,
1210 // and we cannot call a getter from a getter in PHP.
1211 $customdata = (array) $cm->get_custom_data();
1212 // Return early if the plugin does not define custom completion rules.
1213 if (empty($customdata['customcompletionrules'])) {
1214 return $data;
1217 // Return early if the activity modules doe not implement the activity_custom_completion class.
1218 $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cm->modname);
1219 if (!$cmcompletionclass) {
1220 return $data;
1223 /** @var activity_custom_completion $customcmcompletion */
1224 $customcmcompletion = new $cmcompletionclass($cm, $userid, $data);
1225 foreach ($customdata['customcompletionrules'] as $rule => $enabled) {
1226 if (!$enabled) {
1227 // Skip inactive completion rules.
1228 continue;
1230 // Get this custom completion rule's completion state.
1231 $data['customcompletion'][$rule] = $customcmcompletion->get_state($rule);
1234 return $data;
1238 * Updates completion data for a particular coursemodule and user (user is
1239 * determined from $data).
1241 * (Internal function. Not private, so we can unit-test it.)
1243 * @param stdClass|cm_info $cm Activity
1244 * @param stdClass $data Data about completion for that user
1245 * @param bool $isbulkupdate If bulk grade update is happening.
1247 public function internal_set_data($cm, $data, $isbulkupdate = false) {
1248 global $USER, $DB, $CFG;
1249 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_activity.php');
1251 $transaction = $DB->start_delegated_transaction();
1252 if (!$data->id) {
1253 // Check there isn't really a row
1254 $data->id = $DB->get_field('course_modules_completion', 'id',
1255 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1257 if (!$data->id) {
1258 // Didn't exist before, needs creating
1259 $data->id = $DB->insert_record('course_modules_completion', $data);
1260 } else {
1261 // Has real (nonzero) id meaning that a database row exists, update
1262 $DB->update_record('course_modules_completion', $data);
1264 $dataview = new stdClass();
1265 $dataview->coursemoduleid = $data->coursemoduleid;
1266 $dataview->userid = $data->userid;
1267 $dataview->id = $DB->get_field('course_modules_viewed', 'id',
1268 ['coursemoduleid' => $dataview->coursemoduleid, 'userid' => $dataview->userid]);
1269 if (!$data->viewed && $dataview->id) {
1270 $DB->delete_records('course_modules_viewed', ['id' => $dataview->id]);
1273 if (!$dataview->id && $data->viewed) {
1274 $dataview->timecreated = time();
1275 $dataview->id = $DB->insert_record('course_modules_viewed', $dataview);
1277 $transaction->allow_commit();
1279 $cmcontext = context_module::instance($data->coursemoduleid);
1281 $completioncache = cache::make('core', 'completion');
1282 $cachekey = "{$data->userid}_{$cm->course}";
1283 if ($data->userid == $USER->id) {
1284 // Fetch other completion data to cache (e.g. require grade completion status, custom completion rule statues).
1285 $cminfo = cm_info::create($cm, $data->userid); // Make sure we're working on a cm_info object.
1286 $otherdata = $this->get_other_cm_completion_data($cminfo, $data->userid);
1287 foreach ($otherdata as $key => $value) {
1288 $data->$key = $value;
1291 // Update module completion in user's cache.
1292 if (!($cachedata = $completioncache->get($cachekey))
1293 || $cachedata['cacherev'] != $this->course->cacherev) {
1294 $cachedata = array('cacherev' => $this->course->cacherev);
1296 $cachedata[$cm->id] = (array) $data;
1297 $cachedata[$cm->id]['other_cm_completion_data_fetched'] = true;
1298 $completioncache->set($cachekey, $cachedata);
1300 // reset modinfo for user (no need to call rebuild_course_cache())
1301 get_fast_modinfo($cm->course, 0, true);
1302 } else {
1303 // Remove another user's completion cache for this course.
1304 $completioncache->delete($cachekey);
1307 // For single user actions the code must reevaluate some completion state instantly, see MDL-32103.
1308 if ($isbulkupdate) {
1309 return;
1310 } else {
1311 $userdata = ['userid' => $data->userid, 'courseid' => $this->course_id];
1312 $coursecompletionid = \core_completion\api::mark_course_completions_activity_criteria($userdata);
1313 if ($coursecompletionid) {
1314 aggregate_completions($coursecompletionid);
1318 // Trigger an event for course module completion changed.
1319 $event = \core\event\course_module_completion_updated::create(array(
1320 'objectid' => $data->id,
1321 'context' => $cmcontext,
1322 'relateduserid' => $data->userid,
1323 'other' => array(
1324 'relateduserid' => $data->userid,
1325 'overrideby' => $data->overrideby,
1326 'completionstate' => $data->completionstate
1329 $event->add_record_snapshot('course_modules_completion', $data);
1330 $event->trigger();
1334 * Return whether or not the course has activities with completion enabled.
1336 * @return boolean true when there is at least one activity with completion enabled.
1338 public function has_activities() {
1339 $modinfo = get_fast_modinfo($this->course);
1340 foreach ($modinfo->get_cms() as $cm) {
1341 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1342 return true;
1345 return false;
1349 * Obtains a list of activities for which completion is enabled on the
1350 * course. The list is ordered by the section order of those activities.
1352 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1353 * empty array if none
1355 public function get_activities() {
1356 $modinfo = get_fast_modinfo($this->course);
1357 $result = array();
1358 foreach ($modinfo->get_cms() as $cm) {
1359 if ($cm->completion != COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) {
1360 $result[$cm->id] = $cm;
1363 return $result;
1367 * Checks to see if the userid supplied has a tracked role in
1368 * this course
1370 * @param int $userid User id
1371 * @return bool
1373 public function is_tracked_user($userid) {
1374 return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1378 * Returns the number of users whose progress is tracked in this course.
1380 * Optionally supply a search's where clause, or a group id.
1382 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1383 * @param array $whereparams Where clause params
1384 * @param int $groupid Group id
1385 * @return int Number of tracked users
1387 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1388 global $DB;
1390 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1391 context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1392 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1393 if ($where) {
1394 $sql .= " WHERE $where";
1397 $params = array_merge($enrolledparams, $whereparams);
1398 return $DB->count_records_sql($sql, $params);
1402 * Return array of users whose progress is tracked in this course.
1404 * Optionally supply a search's where clause, group id, sorting, paging.
1406 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1407 * @param array $whereparams Where clause params (optional)
1408 * @param int $groupid Group ID to restrict to (optional)
1409 * @param string $sort Order by clause (optional)
1410 * @param int $limitfrom Result start (optional)
1411 * @param int $limitnum Result max size (optional)
1412 * @param context $extracontext If set, includes extra user information fields
1413 * as appropriate to display for current user in this context
1414 * @return array Array of user objects with user fields (including all identity fields)
1416 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1417 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1419 global $DB;
1421 list($enrolledsql, $params) = get_enrolled_sql(
1422 context_course::instance($this->course->id),
1423 'moodle/course:isincompletionreports', $groupid, true);
1425 $userfieldsapi = \core_user\fields::for_identity($extracontext)->with_name()->excluding('id', 'idnumber');
1426 $fieldssql = $userfieldsapi->get_sql('u', true);
1427 $sql = 'SELECT u.id, u.idnumber ' . $fieldssql->selects;
1428 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1430 if ($where) {
1431 $sql .= " AND $where";
1432 $params = array_merge($params, $whereparams);
1435 $sql .= $fieldssql->joins;
1436 $params = array_merge($params, $fieldssql->params);
1438 if ($sort) {
1439 $sql .= " ORDER BY $sort";
1442 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1446 * Obtains progress information across a course for all users on that course, or
1447 * for all users in a specific group. Intended for use when displaying progress.
1449 * This includes only users who, in course context, have one of the roles for
1450 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1452 * Users are included (in the first array) even if they do not have
1453 * completion progress for any course-module.
1455 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1456 * last name
1457 * @param string $where Where clause sql (optional)
1458 * @param array $where_params Where clause params (optional)
1459 * @param int $groupid Group ID or 0 (default)/false for all groups
1460 * @param int $pagesize Number of users to actually return (optional)
1461 * @param int $start User to start at if paging (optional)
1462 * @param context $extracontext If set, includes extra user information fields
1463 * as appropriate to display for current user in this context
1464 * @return stdClass with ->total and ->start (same as $start) and ->users;
1465 * an array of user objects (like mdl_user id, firstname, lastname)
1466 * containing an additional ->progress array of coursemoduleid => completionstate
1468 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1469 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1470 global $CFG, $DB;
1472 // Get list of applicable users
1473 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1474 $start, $pagesize, $extracontext);
1476 // Get progress information for these users in groups of 1, 000 (if needed)
1477 // to avoid making the SQL IN too long
1478 $results = array();
1479 $userids = array();
1480 foreach ($users as $user) {
1481 $userids[] = $user->id;
1482 $results[$user->id] = $user;
1483 $results[$user->id]->progress = array();
1486 for($i=0; $i<count($userids); $i+=1000) {
1487 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1489 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1490 array_splice($params, 0, 0, array($this->course->id));
1491 $rs = $DB->get_recordset_sql("
1492 SELECT
1493 cmc.*
1494 FROM
1495 {course_modules} cm
1496 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1497 WHERE
1498 cm.course=? AND cmc.userid $insql", $params);
1499 foreach ($rs as $progress) {
1500 $progress = (object)$progress;
1501 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1503 $rs->close();
1506 return $results;
1510 * Called by grade code to inform the completion system when a grade has
1511 * been changed. If the changed grade is used to determine completion for
1512 * the course-module, then the completion status will be updated.
1514 * @param stdClass|cm_info $cm Course-module for item that owns grade
1515 * @param grade_item $item Grade item
1516 * @param stdClass $grade
1517 * @param bool $deleted
1518 * @param bool $isbulkupdate If bulk grade update is happening.
1520 public function inform_grade_changed($cm, $item, $grade, $deleted, $isbulkupdate = false) {
1521 // Bail out now if completion is not enabled for course-module, it is enabled
1522 // but is set to manual, grade is not used to compute completion, or this
1523 // is a different numbered grade
1524 if (!$this->is_enabled($cm) ||
1525 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1526 is_null($cm->completiongradeitemnumber) ||
1527 $item->itemnumber != $cm->completiongradeitemnumber) {
1528 return;
1531 // What is the expected result based on this grade?
1532 if ($deleted) {
1533 // Grade being deleted, so only change could be to make it incomplete
1534 $possibleresult = COMPLETION_INCOMPLETE;
1535 } else {
1536 $possibleresult = self::internal_get_grade_state($item, $grade);
1539 // OK, let's update state based on this
1540 $this->update_state($cm, $possibleresult, $grade->userid, false, $isbulkupdate);
1544 * Calculates the completion state that would result from a graded item
1545 * (where grade-based completion is turned on) based on the actual grade
1546 * and settings.
1548 * Internal function. Not private, so we can unit-test it.
1550 * @param grade_item $item an instance of grade_item
1551 * @param grade_grade $grade an instance of grade_grade
1552 * @param bool $returnpassfail If course module has pass grade completion criteria
1553 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1555 public static function internal_get_grade_state($item, $grade, bool $returnpassfail = false) {
1556 // If no grade is supplied or the grade doesn't have an actual value, then
1557 // this is not complete.
1558 if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1559 return COMPLETION_INCOMPLETE;
1562 // Conditions to show pass/fail:
1563 // a) Completion criteria to achieve pass grade is enabled
1564 // or
1565 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1566 // b) Grade is visible (neither hidden nor hidden-until)
1567 if ($item->gradepass && $item->gradepass > 0.000009 && ($returnpassfail || !$item->hidden)) {
1568 // Use final grade if set otherwise raw grade
1569 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1571 // We are displaying and tracking pass/fail
1572 if ($score >= $item->gradepass) {
1573 return COMPLETION_COMPLETE_PASS;
1574 } else if ($item->hidden) {
1575 return COMPLETION_COMPLETE_FAIL_HIDDEN;
1576 } else {
1577 return COMPLETION_COMPLETE_FAIL;
1579 } else {
1580 // Not displaying pass/fail, so just if there is a grade
1581 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1582 // Grade exists, so maybe complete now
1583 return COMPLETION_COMPLETE;
1584 } else {
1585 // Grade does not exist, so maybe incomplete now
1586 return COMPLETION_INCOMPLETE;
1592 * Aggregate activity completion state
1594 * @param int $type Aggregation type (COMPLETION_* constant)
1595 * @param bool $old Old state
1596 * @param bool $new New state
1597 * @return bool
1599 public static function aggregate_completion_states($type, $old, $new) {
1600 if ($type == COMPLETION_AND) {
1601 return $old && $new;
1602 } else {
1603 return $old || $new;
1608 * This is to be used only for system errors (things that shouldn't happen)
1609 * and not user-level errors.
1611 * @global type $CFG
1612 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1613 * @throws moodle_exception Exception with the error string as debug info
1615 public function internal_systemerror($error) {
1616 global $CFG;
1617 throw new moodle_exception('err_system','completion',
1618 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1622 * Get completion data include viewed field.
1624 * @param int $coursemoduleid The course module id.
1625 * @param int $userid The User ID.
1626 * @param array $defaultdata Default data completion.
1627 * @return array Data completion retrieved.
1629 public function get_completion_data(int $coursemoduleid, int $userid, array $defaultdata): array {
1630 global $DB;
1632 // MySQL doesn't support FULL JOIN syntax, so we use UNION in the below SQL to help MySQL.
1633 $sql = "SELECT cmc.*, cmv.coursemoduleid as cmvcoursemoduleid, cmv.userid as cmvuserid
1634 FROM {course_modules_completion} cmc
1635 LEFT JOIN {course_modules_viewed} cmv ON cmc.coursemoduleid = cmv.coursemoduleid AND cmc.userid = cmv.userid
1636 WHERE cmc.coursemoduleid = :cmccoursemoduleid AND cmc.userid = :cmcuserid
1637 UNION
1638 SELECT cmc2.*, cmv2.coursemoduleid as cmvcoursemoduleid, cmv2.userid as cmvuserid
1639 FROM {course_modules_completion} cmc2
1640 RIGHT JOIN {course_modules_viewed} cmv2
1641 ON cmc2.coursemoduleid = cmv2.coursemoduleid AND cmc2.userid = cmv2.userid
1642 WHERE cmv2.coursemoduleid = :cmvcoursemoduleid AND cmv2.userid = :cmvuserid";
1644 $data = $DB->get_record_sql($sql, ['cmccoursemoduleid' => $coursemoduleid, 'cmcuserid' => $userid,
1645 'cmvcoursemoduleid' => $coursemoduleid, 'cmvuserid' => $userid]);
1647 if (!$data) {
1648 $data = $defaultdata;
1649 } else {
1650 if (empty($data->coursemoduleid) && empty($data->userid)) {
1651 $data->coursemoduleid = $data->cmvcoursemoduleid;
1652 $data->userid = $data->cmvuserid;
1654 unset($data->cmvcoursemoduleid);
1655 unset($data->cmvuserid);
1657 // When reseting all state in the completion, we need to keep current view state.
1658 $data->viewed = 1;
1661 return (array)$data;
1666 * Aggregate criteria status's as per configured aggregation method.
1668 * @param int $method COMPLETION_AGGREGATION_* constant.
1669 * @param bool $data Criteria completion status.
1670 * @param bool|null $state Aggregation state.
1672 function completion_cron_aggregate($method, $data, &$state) {
1673 if ($method == COMPLETION_AGGREGATION_ALL) {
1674 if ($data && $state !== false) {
1675 $state = true;
1676 } else {
1677 $state = false;
1679 } else if ($method == COMPLETION_AGGREGATION_ANY) {
1680 if ($data) {
1681 $state = true;
1682 } else if (!$data && $state === null) {
1683 $state = false;
1689 * Aggregate courses completions. This function is called when activity completion status is updated
1690 * for single user. Also when regular completion task runs it aggregates completions for all courses and users.
1692 * @param int $coursecompletionid Course completion ID to update (if 0 - update for all courses and users)
1693 * @param bool $mtraceprogress To output debug info
1694 * @since Moodle 4.0
1696 function aggregate_completions(int $coursecompletionid, bool $mtraceprogress = false) {
1697 global $DB;
1699 if (!$coursecompletionid && $mtraceprogress) {
1700 mtrace('Aggregating completions');
1702 // Save time started.
1703 $timestarted = time();
1705 // Grab all criteria and their associated criteria completions.
1706 $sql = "SELECT DISTINCT c.id AS courseid, cr.id AS criteriaid, cco.userid, cr.criteriatype, ccocr.timecompleted
1707 FROM {course_completion_criteria} cr
1708 INNER JOIN {course} c ON cr.course = c.id
1709 INNER JOIN {course_completions} cco ON cco.course = c.id
1710 LEFT JOIN {course_completion_crit_compl} ccocr
1711 ON ccocr.criteriaid = cr.id AND cco.userid = ccocr.userid
1712 WHERE c.enablecompletion = 1
1713 AND cco.timecompleted IS NULL
1714 AND cco.reaggregate > 0";
1716 if ($coursecompletionid) {
1717 $sql .= " AND cco.id = ?";
1718 $param = $coursecompletionid;
1719 } else {
1720 $sql .= " AND cco.reaggregate < ? ORDER BY courseid, cco.userid";
1721 $param = $timestarted;
1723 $rs = $DB->get_recordset_sql($sql, [$param]);
1725 // Check if result is empty.
1726 if (!$rs->valid()) {
1727 $rs->close();
1728 return;
1731 $currentuser = null;
1732 $currentcourse = null;
1733 $completions = [];
1734 while (1) {
1735 // Grab records for current user/course.
1736 foreach ($rs as $record) {
1737 // If we are still grabbing the same users completions.
1738 if ($record->userid === $currentuser && $record->courseid === $currentcourse) {
1739 $completions[$record->criteriaid] = $record;
1740 } else {
1741 break;
1745 // Aggregate.
1746 if (!empty($completions)) {
1747 if (!$coursecompletionid && $mtraceprogress) {
1748 mtrace('Aggregating completions for user ' . $currentuser . ' in course ' . $currentcourse);
1751 // Get course info object.
1752 $info = new \completion_info((object)['id' => $currentcourse]);
1754 // Setup aggregation.
1755 $overall = $info->get_aggregation_method();
1756 $activity = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ACTIVITY);
1757 $prerequisite = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_COURSE);
1758 $role = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ROLE);
1760 $overallstatus = null;
1761 $activitystatus = null;
1762 $prerequisitestatus = null;
1763 $rolestatus = null;
1765 // Get latest timecompleted.
1766 $timecompleted = null;
1768 // Check each of the criteria.
1769 foreach ($completions as $params) {
1770 $timecompleted = max($timecompleted, $params->timecompleted);
1771 $completion = new \completion_criteria_completion((array)$params, false);
1773 // Handle aggregation special cases.
1774 if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) {
1775 completion_cron_aggregate($activity, $completion->is_complete(), $activitystatus);
1776 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) {
1777 completion_cron_aggregate($prerequisite, $completion->is_complete(), $prerequisitestatus);
1778 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ROLE) {
1779 completion_cron_aggregate($role, $completion->is_complete(), $rolestatus);
1780 } else {
1781 completion_cron_aggregate($overall, $completion->is_complete(), $overallstatus);
1785 // Include role criteria aggregation in overall aggregation.
1786 if ($rolestatus !== null) {
1787 completion_cron_aggregate($overall, $rolestatus, $overallstatus);
1790 // Include activity criteria aggregation in overall aggregation.
1791 if ($activitystatus !== null) {
1792 completion_cron_aggregate($overall, $activitystatus, $overallstatus);
1795 // Include prerequisite criteria aggregation in overall aggregation.
1796 if ($prerequisitestatus !== null) {
1797 completion_cron_aggregate($overall, $prerequisitestatus, $overallstatus);
1800 // If aggregation status is true, mark course complete for user.
1801 if ($overallstatus) {
1802 if (!$coursecompletionid && $mtraceprogress) {
1803 mtrace('Marking complete');
1806 $ccompletion = new \completion_completion([
1807 'course' => $params->courseid,
1808 'userid' => $params->userid
1810 $ccompletion->mark_complete($timecompleted);
1814 // If this is the end of the recordset, break the loop.
1815 if (!$rs->valid()) {
1816 $rs->close();
1817 break;
1820 // New/next user, update user details, reset completions.
1821 $currentuser = $record->userid;
1822 $currentcourse = $record->courseid;
1823 $completions = [];
1824 $completions[$record->criteriaid] = $record;
1827 // Mark all users as aggregated.
1828 if ($coursecompletionid) {
1829 $select = "reaggregate > 0 AND id = ?";
1830 $param = $coursecompletionid;
1831 } else {
1832 $select = "reaggregate > 0 AND reaggregate < ?";
1833 $param = $timestarted;
1834 if (PHPUNIT_TEST) {
1835 // MDL-33320: for instant completions we need aggregate to work in a single run.
1836 $DB->set_field('course_completions', 'reaggregate', $timestarted - 2);
1839 $DB->set_field_select('course_completions', 'reaggregate', 0, $select, [$param]);