Merge branch 'MDL-76220-master' of https://github.com/ferranrecio/moodle
[moodle.git] / lib / completionlib.php
blob94cd4b0c9244b8f8bbc85a888f45f6403b25ed4e
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 * The effect of this change to completion status is unknown.
93 * A completion effect changes (used only in update_state)
95 define('COMPLETION_UNKNOWN', -1);
96 /**
97 * The user's grade has changed, so their new state might be
98 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
99 * A completion effect changes (used only in update_state)
101 define('COMPLETION_GRADECHANGE', -2);
104 * User must view this activity.
105 * Whether view is required to create an activity (course_modules/completionview)
107 define('COMPLETION_VIEW_REQUIRED', 1);
109 * User does not need to view this activity
110 * Whether view is required to create an activity (course_modules/completionview)
112 define('COMPLETION_VIEW_NOT_REQUIRED', 0);
115 * User has viewed this activity.
116 * Completion viewed state (course_modules_completion/viewed)
118 define('COMPLETION_VIEWED', 1);
120 * User has not viewed this activity.
121 * Completion viewed state (course_modules_completion/viewed)
123 define('COMPLETION_NOT_VIEWED', 0);
126 * Completion details should be ORed together and you should return false if
127 * none apply.
129 define('COMPLETION_OR', false);
131 * Completion details should be ANDed together and you should return true if
132 * none apply
134 define('COMPLETION_AND', true);
137 * Course completion criteria aggregation method.
139 define('COMPLETION_AGGREGATION_ALL', 1);
141 * Course completion criteria aggregation method.
143 define('COMPLETION_AGGREGATION_ANY', 2);
146 * Completion conditions will be displayed to user.
148 define('COMPLETION_SHOW_CONDITIONS', 1);
151 * Completion conditions will be hidden from user.
153 define('COMPLETION_HIDE_CONDITIONS', 0);
156 * Utility function for checking if the logged in user can view
157 * another's completion data for a particular course
159 * @access public
160 * @param int $userid Completion data's owner
161 * @param mixed $course Course object or Course ID (optional)
162 * @return boolean
164 function completion_can_view_data($userid, $course = null) {
165 global $USER;
167 if (!isloggedin()) {
168 return false;
171 if (!is_object($course)) {
172 $cid = $course;
173 $course = new stdClass();
174 $course->id = $cid;
177 // Check if this is the site course
178 if ($course->id == SITEID) {
179 $course = null;
182 // Check if completion is enabled
183 if ($course) {
184 $cinfo = new completion_info($course);
185 if (!$cinfo->is_enabled()) {
186 return false;
188 } else {
189 if (!completion_info::is_enabled_for_site()) {
190 return false;
194 // Is own user's data?
195 if ($USER->id == $userid) {
196 return true;
199 // Check capabilities
200 $personalcontext = context_user::instance($userid);
202 if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
203 return true;
204 } elseif (has_capability('report/completion:view', $personalcontext)) {
205 return true;
208 if ($course->id) {
209 $coursecontext = context_course::instance($course->id);
210 } else {
211 $coursecontext = context_system::instance();
214 if (has_capability('report/completion:view', $coursecontext)) {
215 return true;
218 return false;
223 * Class represents completion information for a course.
225 * Does not contain any data, so you can safely construct it multiple times
226 * without causing any problems.
228 * @package core
229 * @category completion
230 * @copyright 2008 Sam Marshall
231 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
233 class completion_info {
235 /* @var stdClass Course object passed during construction */
236 private $course;
238 /* @var int Course id */
239 public $course_id;
241 /* @var array Completion criteria {@link completion_info::get_criteria()} */
242 private $criteria;
245 * Return array of aggregation methods
246 * @return array
248 public static function get_aggregation_methods() {
249 return array(
250 COMPLETION_AGGREGATION_ALL => get_string('all'),
251 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
256 * Constructs with course details.
258 * When instantiating a new completion info object you must provide a course
259 * object with at least id, and enablecompletion properties. Property
260 * cacherev is needed if you check completion of the current user since
261 * it is used for cache validation.
263 * @param stdClass $course Moodle course object.
265 public function __construct($course) {
266 $this->course = $course;
267 $this->course_id = $course->id;
271 * Determines whether completion is enabled across entire site.
273 * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
274 * COMPLETION_DISABLED (false) if it's complete
276 public static function is_enabled_for_site() {
277 global $CFG;
278 return !empty($CFG->enablecompletion);
282 * Checks whether completion is enabled in a particular course and possibly
283 * activity.
285 * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
286 * completion enable state.
287 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
288 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
289 * for a course-module.
291 public function is_enabled($cm = null) {
292 global $CFG, $DB;
294 // First check global completion
295 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
296 return COMPLETION_DISABLED;
299 // Load data if we do not have enough
300 if (!isset($this->course->enablecompletion)) {
301 $this->course = get_course($this->course_id);
304 // Check course completion
305 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
306 return COMPLETION_DISABLED;
309 // If there was no $cm and we got this far, then it's enabled
310 if (!$cm) {
311 return COMPLETION_ENABLED;
314 // Return course-module completion value
315 return $cm->completion;
319 * Displays the 'Your progress' help icon, if completion tracking is enabled.
320 * Just prints the result of display_help_icon().
322 * @deprecated since Moodle 2.0 - Use display_help_icon instead.
324 public function print_help_icon() {
325 debugging('The function print_help_icon() is deprecated, please do not use it anymore.',
326 DEBUG_DEVELOPER);
327 print $this->display_help_icon();
331 * Returns the 'Your progress' help icon, if completion tracking is enabled.
333 * @return string HTML code for help icon, or blank if not needed
334 * @deprecated since Moodle 4.0 - The 'Your progress' info isn't displayed any more.
336 public function display_help_icon() {
337 global $PAGE, $OUTPUT, $USER;
338 debugging('The function display_help_icon() is deprecated, please do not use it anymore.',
339 DEBUG_DEVELOPER);
340 $result = '';
341 if ($this->is_enabled() && !$PAGE->user_is_editing() && $this->is_tracked_user($USER->id) && isloggedin() &&
342 !isguestuser()) {
343 $result .= html_writer::tag('div', get_string('yourprogress','completion') .
344 $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
345 'class' => 'completionprogress'));
347 return $result;
351 * Get a course completion for a user
353 * @param int $user_id User id
354 * @param int $criteriatype Specific criteria type to return
355 * @return bool|completion_criteria_completion returns false on fail
357 public function get_completion($user_id, $criteriatype) {
358 $completions = $this->get_completions($user_id, $criteriatype);
360 if (empty($completions)) {
361 return false;
362 } elseif (count($completions) > 1) {
363 throw new \moodle_exception('multipleselfcompletioncriteria', 'completion');
366 return $completions[0];
370 * Get all course criteria's completion objects for a user
372 * @param int $user_id User id
373 * @param int $criteriatype Specific criteria type to return (optional)
374 * @return array
376 public function get_completions($user_id, $criteriatype = null) {
377 $criteria = $this->get_criteria($criteriatype);
379 $completions = array();
381 foreach ($criteria as $criterion) {
382 $params = array(
383 'course' => $this->course_id,
384 'userid' => $user_id,
385 'criteriaid' => $criterion->id
388 $completion = new completion_criteria_completion($params);
389 $completion->attach_criteria($criterion);
391 $completions[] = $completion;
394 return $completions;
398 * Get completion object for a user and a criteria
400 * @param int $user_id User id
401 * @param completion_criteria $criteria Criteria object
402 * @return completion_criteria_completion
404 public function get_user_completion($user_id, $criteria) {
405 $params = array(
406 'course' => $this->course_id,
407 'userid' => $user_id,
408 'criteriaid' => $criteria->id,
411 $completion = new completion_criteria_completion($params);
412 return $completion;
416 * Check if course has completion criteria set
418 * @return bool Returns true if there are criteria
420 public function has_criteria() {
421 $criteria = $this->get_criteria();
423 return (bool) count($criteria);
427 * Get course completion criteria
429 * @param int $criteriatype Specific criteria type to return (optional)
431 public function get_criteria($criteriatype = null) {
433 // Fill cache if empty
434 if (!is_array($this->criteria)) {
435 global $DB;
437 $params = array(
438 'course' => $this->course->id
441 // Load criteria from database
442 $records = (array)$DB->get_records('course_completion_criteria', $params);
444 // Order records so activities are in the same order as they appear on the course view page.
445 if ($records) {
446 $activitiesorder = array_keys(get_fast_modinfo($this->course)->get_cms());
447 usort($records, function ($a, $b) use ($activitiesorder) {
448 $aidx = ($a->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
449 array_search($a->moduleinstance, $activitiesorder) : false;
450 $bidx = ($b->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
451 array_search($b->moduleinstance, $activitiesorder) : false;
452 if ($aidx === false || $bidx === false || $aidx == $bidx) {
453 return 0;
455 return ($aidx < $bidx) ? -1 : 1;
459 // Build array of criteria objects
460 $this->criteria = array();
461 foreach ($records as $record) {
462 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
466 // If after all criteria
467 if ($criteriatype === null) {
468 return $this->criteria;
471 // If we are only after a specific criteria type
472 $criteria = array();
473 foreach ($this->criteria as $criterion) {
475 if ($criterion->criteriatype != $criteriatype) {
476 continue;
479 $criteria[$criterion->id] = $criterion;
482 return $criteria;
486 * Get aggregation method
488 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
489 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
491 public function get_aggregation_method($criteriatype = null) {
492 $params = array(
493 'course' => $this->course_id,
494 'criteriatype' => $criteriatype
497 $aggregation = new completion_aggregation($params);
499 if (!$aggregation->id) {
500 $aggregation->method = COMPLETION_AGGREGATION_ALL;
503 return $aggregation->method;
507 * @deprecated since Moodle 2.8 MDL-46290.
509 public function get_incomplete_criteria() {
510 throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
514 * Clear old course completion criteria
516 public function clear_criteria() {
517 global $DB;
519 // Remove completion criteria records for the course itself, and any records that refer to the course.
520 $select = 'course = :course OR (criteriatype = :type AND courseinstance = :courseinstance)';
521 $params = [
522 'course' => $this->course_id,
523 'type' => COMPLETION_CRITERIA_TYPE_COURSE,
524 'courseinstance' => $this->course_id,
527 $DB->delete_records_select('course_completion_criteria', $select, $params);
528 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
530 $this->delete_course_completion_data();
534 * Has the supplied user completed this course
536 * @param int $user_id User's id
537 * @return boolean
539 public function is_course_complete($user_id) {
540 $params = array(
541 'userid' => $user_id,
542 'course' => $this->course_id
545 $ccompletion = new completion_completion($params);
546 return $ccompletion->is_complete();
550 * Check whether the supplied user can override the activity completion statuses within the current course.
552 * @param stdClass $user The user object.
553 * @return bool True if the user can override, false otherwise.
555 public function user_can_override_completion($user) {
556 return has_capability('moodle/course:overridecompletion', context_course::instance($this->course_id), $user);
560 * Updates (if necessary) the completion state of activity $cm for the given
561 * user.
563 * For manual completion, this function is called when completion is toggled
564 * with $possibleresult set to the target state.
566 * For automatic completion, this function should be called every time a module
567 * does something which might influence a user's completion state. For example,
568 * if a forum provides options for marking itself 'completed' once a user makes
569 * N posts, this function should be called every time a user makes a new post.
570 * [After the post has been saved to the database]. When calling, you do not
571 * need to pass in the new completion state. Instead this function carries out completion
572 * calculation by checking grades and viewed state itself, and calling the involved module
573 * via mod_{modulename}\\completion\\custom_completion::get_overall_completion_state() to
574 * check module-specific conditions.
576 * @param stdClass|cm_info $cm Course-module
577 * @param int $possibleresult Expected completion result. If the event that
578 * has just occurred (e.g. add post) can only result in making the activity
579 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
580 * has just occurred (e.g. delete post) can only result in making the activity
581 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
582 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
583 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
584 * processing early if the user's completion state already matches the expected
585 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
586 * must be used; these directly set the specified state.
587 * @param int $userid User ID to be updated. Default 0 = current user
588 * @param bool $override Whether manually overriding the existing completion state.
589 * @param bool $isbulkupdate If bulk grade update is happening.
590 * @return void
591 * @throws moodle_exception if trying to override without permission.
593 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0,
594 $override = false, $isbulkupdate = false) {
595 global $USER;
597 // Do nothing if completion is not enabled for that activity
598 if (!$this->is_enabled($cm)) {
599 return;
602 // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
603 if ($override) {
604 if (!$this->user_can_override_completion($USER)) {
605 throw new required_capability_exception(context_course::instance($this->course_id),
606 'moodle/course:overridecompletion', 'nopermission', '');
610 // Default to current user if one is not provided.
611 if ($userid == 0) {
612 $userid = $USER->id;
615 // Delete the cm's cached completion data for this user if automatic completion is enabled.
616 // This ensures any changes to the status of individual completion conditions in the activity will be fetched.
617 if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC) {
618 $completioncache = cache::make('core', 'completion');
619 $completionkey = $userid . '_' . $this->course->id;
620 $completiondata = $completioncache->get($completionkey);
622 if ($completiondata !== false) {
623 unset($completiondata[$cm->id]);
624 $completioncache->set($completionkey, $completiondata);
628 // Get current value of completion state and do nothing if it's same as
629 // the possible result of this change. If the change is to COMPLETE and the
630 // current value is one of the COMPLETE_xx subtypes, ignore that as well
631 $current = $this->get_data($cm, false, $userid);
632 if ($possibleresult == $current->completionstate ||
633 ($possibleresult == COMPLETION_COMPLETE &&
634 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
635 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
636 return;
639 // The activity completion alters the course state cache for this particular user.
640 $course = get_course($cm->course);
641 if ($course) {
642 course_format::session_cache_reset($course);
645 // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
646 // unless processing another override.
647 // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
648 // overridden to INCOMPLETE to still be processed by normal completion triggers.
649 if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC && !is_null($current->overrideby)
650 && $current->completionstate == COMPLETION_COMPLETE && !$override) {
651 return;
654 // For manual tracking, or if overriding the completion state, we set the state directly.
655 if ($cm->completion == COMPLETION_TRACKING_MANUAL || $override) {
656 switch($possibleresult) {
657 case COMPLETION_COMPLETE:
658 case COMPLETION_INCOMPLETE:
659 $newstate = $possibleresult;
660 break;
661 default:
662 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
665 } else {
666 $newstate = $this->internal_get_state($cm, $userid, $current);
669 // If the overall completion state has changed, update it in the cache.
670 if ($newstate != $current->completionstate) {
671 $current->completionstate = $newstate;
672 $current->timemodified = time();
673 $current->overrideby = $override ? $USER->id : null;
674 $this->internal_set_data($cm, $current, $isbulkupdate);
679 * Calculates the completion state for an activity and user.
681 * Internal function. Not private, so we can unit-test it.
683 * @param stdClass|cm_info $cm Activity
684 * @param int $userid ID of user
685 * @param stdClass $current Previous completion information from database
686 * @return mixed
688 public function internal_get_state($cm, $userid, $current) {
689 global $USER, $DB;
691 // Get user ID
692 if (!$userid) {
693 $userid = $USER->id;
696 $newstate = COMPLETION_COMPLETE;
697 if ($cm instanceof stdClass) {
698 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it.
699 if (!isset($cm->modname)) {
700 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
702 // Some functions call this method and pass $cm as an object with ID only. Make sure course is set as well.
703 if (!isset($cm->course)) {
704 $cm->course = $this->course_id;
707 // Make sure we're using a cm_info object.
708 $cminfo = cm_info::create($cm, $userid);
709 $completionstate = $this->get_core_completion_state($cminfo, $userid);
711 if (plugin_supports('mod', $cminfo->modname, FEATURE_COMPLETION_HAS_RULES)) {
712 $response = true;
713 $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cminfo->modname);
714 if ($cmcompletionclass) {
715 /** @var activity_custom_completion $cmcompletion */
716 $cmcompletion = new $cmcompletionclass($cminfo, $userid, $completionstate);
717 $response = $cmcompletion->get_overall_completion_state() != COMPLETION_INCOMPLETE;
718 } else {
719 // Fallback to the get_completion_state callback.
720 $cmcompletionclass = "mod_{$cminfo->modname}\\completion\\custom_completion";
721 $function = $cminfo->modname . '_get_completion_state';
722 if (!function_exists($function)) {
723 $this->internal_systemerror("Module {$cminfo->modname} claims to support FEATURE_COMPLETION_HAS_RULES " .
724 "but does not implement the custom completion class $cmcompletionclass which extends " .
725 "\core_completion\activity_custom_completion.");
727 debugging("*_get_completion_state() callback functions such as $function have been deprecated and should no " .
728 "longer be used. Please implement the custom completion class $cmcompletionclass which extends " .
729 "\core_completion\activity_custom_completion.", DEBUG_DEVELOPER);
730 $response = $function($this->course, $cm, $userid, COMPLETION_AND, $completionstate);
733 if (!$response) {
734 return COMPLETION_INCOMPLETE;
738 if ($completionstate) {
739 // We have allowed the plugins to do it's thing and run their own checks.
740 // We have now reached a state where we need to AND all the calculated results.
741 // Preference for COMPLETION_COMPLETE_PASS over COMPLETION_COMPLETE for proper indication in reports.
742 $newstate = array_reduce($completionstate, function($carry, $value) {
743 if (in_array(COMPLETION_INCOMPLETE, [$carry, $value])) {
744 return COMPLETION_INCOMPLETE;
745 } else if (in_array(COMPLETION_COMPLETE_FAIL, [$carry, $value])) {
746 return COMPLETION_COMPLETE_FAIL;
747 } else {
748 return in_array(COMPLETION_COMPLETE_PASS, [$carry, $value]) ? COMPLETION_COMPLETE_PASS : $value;
751 }, COMPLETION_COMPLETE);
754 return $newstate;
759 * Fetches the completion state for an activity completion's require grade completion requirement.
761 * @param cm_info $cm The course module information.
762 * @param int $userid The user ID.
763 * @return int The completion state.
765 public function get_grade_completion(cm_info $cm, int $userid): int {
766 global $CFG;
768 require_once($CFG->libdir . '/gradelib.php');
769 $item = grade_item::fetch([
770 'courseid' => $cm->course,
771 'itemtype' => 'mod',
772 'itemmodule' => $cm->modname,
773 'iteminstance' => $cm->instance,
774 'itemnumber' => $cm->completiongradeitemnumber
776 if ($item) {
777 // Fetch 'grades' (will be one or none).
778 $grades = grade_grade::fetch_users_grades($item, [$userid], false);
779 if (empty($grades)) {
780 // No grade for user.
781 return COMPLETION_INCOMPLETE;
783 if (count($grades) > 1) {
784 $this->internal_systemerror("Unexpected result: multiple grades for
785 item '{$item->id}', user '{$userid}'");
787 return self::internal_get_grade_state($item, reset($grades));
790 return COMPLETION_INCOMPLETE;
794 * Marks a module as viewed.
796 * Should be called whenever a module is 'viewed' (it is up to the module how to
797 * determine that). Has no effect if viewing is not set as a completion condition.
799 * Note that this function must be called before you print the page header because
800 * it is possible that the navigation block may depend on it. If you call it after
801 * printing the header, it shows a developer debug warning.
803 * @param stdClass|cm_info $cm Activity
804 * @param int $userid User ID or 0 (default) for current user
805 * @return void
807 public function set_module_viewed($cm, $userid=0) {
808 global $PAGE;
809 if ($PAGE->headerprinted) {
810 debugging('set_module_viewed must be called before header is printed',
811 DEBUG_DEVELOPER);
814 // Don't do anything if view condition is not turned on
815 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
816 return;
819 // Get current completion state
820 $data = $this->get_data($cm, false, $userid);
822 // If we already viewed it, don't do anything unless the completion status is overridden.
823 // If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
824 if ($data->viewed == COMPLETION_VIEWED && empty($data->overrideby)) {
825 return;
828 // OK, change state, save it, and update completion
829 $data->viewed = COMPLETION_VIEWED;
830 $this->internal_set_data($cm, $data);
831 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
835 * Determines how much completion data exists for an activity. This is used when
836 * deciding whether completion information should be 'locked' in the module
837 * editing form.
839 * @param cm_info $cm Activity
840 * @return int The number of users who have completion data stored for this
841 * activity, 0 if none
843 public function count_user_data($cm) {
844 global $DB;
846 return $DB->get_field_sql("
847 SELECT
848 COUNT(1)
849 FROM
850 {course_modules_completion}
851 WHERE
852 coursemoduleid=? AND completionstate<>0", array($cm->id));
856 * Determines how much course completion data exists for a course. This is used when
857 * deciding whether completion information should be 'locked' in the completion
858 * settings form and activity completion settings.
860 * @param int $user_id Optionally only get course completion data for a single user
861 * @return int The number of users who have completion data stored for this
862 * course, 0 if none
864 public function count_course_user_data($user_id = null) {
865 global $DB;
867 $sql = '
868 SELECT
869 COUNT(1)
870 FROM
871 {course_completion_crit_compl}
872 WHERE
873 course = ?
876 $params = array($this->course_id);
878 // Limit data to a single user if an ID is supplied
879 if ($user_id) {
880 $sql .= ' AND userid = ?';
881 $params[] = $user_id;
884 return $DB->get_field_sql($sql, $params);
888 * Check if this course's completion criteria should be locked
890 * @return boolean
892 public function is_course_locked() {
893 return (bool) $this->count_course_user_data();
897 * Deletes all course completion completion data.
899 * Intended to be used when unlocking completion criteria settings.
901 public function delete_course_completion_data() {
902 global $DB;
904 $DB->delete_records('course_completions', array('course' => $this->course_id));
905 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
907 // Difficult to find affected users, just purge all completion cache.
908 cache::make('core', 'completion')->purge();
909 cache::make('core', 'coursecompletion')->purge();
913 * Deletes all activity and course completion data for an entire course
914 * (the below delete_all_state function does this for a single activity).
916 * Used by course reset page.
918 public function delete_all_completion_data() {
919 global $DB;
921 // Delete from database.
922 $DB->delete_records_select('course_modules_completion',
923 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
924 array($this->course_id));
926 // Wipe course completion data too.
927 $this->delete_course_completion_data();
931 * Deletes completion state related to an activity for all users.
933 * Intended for use only when the activity itself is deleted.
935 * @param stdClass|cm_info $cm Activity
937 public function delete_all_state($cm) {
938 global $DB;
940 // Delete from database
941 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
943 // Check if there is an associated course completion criteria
944 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
945 $acriteria = false;
946 foreach ($criteria as $criterion) {
947 if ($criterion->moduleinstance == $cm->id) {
948 $acriteria = $criterion;
949 break;
953 if ($acriteria) {
954 // Delete all criteria completions relating to this activity
955 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
956 $DB->delete_records('course_completions', array('course' => $this->course_id));
959 // Difficult to find affected users, just purge all completion cache.
960 cache::make('core', 'completion')->purge();
961 cache::make('core', 'coursecompletion')->purge();
965 * Recalculates completion state related to an activity for all users.
967 * Intended for use if completion conditions change. (This should be avoided
968 * as it may cause some things to become incomplete when they were previously
969 * complete, with the effect - for example - of hiding a later activity that
970 * was previously available.)
972 * Resetting state of manual tickbox has same result as deleting state for
973 * it.
975 * @param stcClass|cm_info $cm Activity
977 public function reset_all_state($cm) {
978 global $DB;
980 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
981 $this->delete_all_state($cm);
982 return;
984 // Get current list of users with completion state
985 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
986 $keepusers = array();
987 foreach ($rs as $rec) {
988 $keepusers[] = $rec->userid;
990 $rs->close();
992 // Delete all existing state.
993 $this->delete_all_state($cm);
995 // Merge this with list of planned users (according to roles)
996 $trackedusers = $this->get_tracked_users();
997 foreach ($trackedusers as $trackeduser) {
998 $keepusers[] = $trackeduser->id;
1000 $keepusers = array_unique($keepusers);
1002 // Recalculate state for each kept user
1003 foreach ($keepusers as $keepuser) {
1004 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
1009 * Obtains completion data for a particular activity and user (from the
1010 * completion cache if available, or by SQL query)
1012 * @param stdClass|cm_info $cm Activity; only required field is ->id
1013 * @param bool $wholecourse If true (default false) then, when necessary to
1014 * fill the cache, retrieves information from the entire course not just for
1015 * this one activity
1016 * @param int $userid User ID or 0 (default) for current user
1017 * @param null $unused This parameter has been deprecated since 4.0 and should not be used anymore.
1018 * @return object Completion data. Record from course_modules_completion plus other completion statuses such as
1019 * - Completion status for 'must-receive-grade' completion rule.
1020 * - Custom completion statuses defined by the activity module plugin.
1022 public function get_data($cm, $wholecourse = false, $userid = 0, $unused = null) {
1023 global $USER, $DB;
1025 if ($unused !== null) {
1026 debugging('Deprecated argument passed to ' . __FUNCTION__, DEBUG_DEVELOPER);
1029 $completioncache = cache::make('core', 'completion');
1031 // Get user ID
1032 if (!$userid) {
1033 $userid = $USER->id;
1036 // Some call completion_info::get_data and pass $cm as an object with ID only. Make sure course is set as well.
1037 if ($cm instanceof stdClass && !isset($cm->course)) {
1038 $cm->course = $this->course_id;
1040 // Make sure we're working on a cm_info object.
1041 $cminfo = cm_info::create($cm, $userid);
1043 // Create an anonymous function to remove the 'other_cm_completion_data_fetched' key.
1044 $returnfilteredvalue = function(array $value): stdClass {
1045 return (object) array_filter($value, function(string $key): bool {
1046 return $key !== 'other_cm_completion_data_fetched';
1047 }, ARRAY_FILTER_USE_KEY);
1050 // See if requested data is present in cache (use cache for current user only).
1051 $usecache = $userid == $USER->id;
1052 $cacheddata = array();
1053 if ($usecache) {
1054 $key = $userid . '_' . $this->course->id;
1055 if (!isset($this->course->cacherev)) {
1056 $this->course = get_course($this->course_id);
1058 if ($cacheddata = $completioncache->get($key)) {
1059 if ($cacheddata['cacherev'] != $this->course->cacherev) {
1060 // Course structure has been changed since the last caching, forget the cache.
1061 $cacheddata = array();
1062 } else if (isset($cacheddata[$cminfo->id])) {
1063 $data = (array) $cacheddata[$cminfo->id];
1064 if (empty($data['other_cm_completion_data_fetched'])) {
1065 $data += $this->get_other_cm_completion_data($cminfo, $userid);
1066 $data['other_cm_completion_data_fetched'] = true;
1068 // Put in cache.
1069 $cacheddata[$cminfo->id] = $data;
1070 $completioncache->set($key, $cacheddata);
1073 return $returnfilteredvalue($cacheddata[$cminfo->id]);
1078 // Default data to return when no completion data is found.
1079 $defaultdata = [
1080 'id' => 0,
1081 'coursemoduleid' => $cminfo->id,
1082 'userid' => $userid,
1083 'completionstate' => 0,
1084 'viewed' => 0,
1085 'overrideby' => null,
1086 'timemodified' => 0,
1089 // If cached completion data is not found, fetch via SQL.
1090 // Fetch completion data for all of the activities in the course ONLY if we're caching the fetched completion data.
1091 // If we're not caching the completion data, then just fetch the completion data for the user in this course module.
1092 if ($usecache && $wholecourse) {
1093 // Get whole course data for cache.
1094 $alldatabycmc = $DB->get_records_sql("SELECT cm.id AS cmid, cmc.*,
1095 CASE WHEN cmv.id IS NULL THEN 0 ELSE 1 END AS viewed
1096 FROM {course_modules} cm
1097 LEFT JOIN {course_modules_completion} cmc
1098 ON cmc.coursemoduleid = cm.id AND cmc.userid = ?
1099 LEFT JOIN {course_modules_viewed} cmv
1100 ON cmv.coursemoduleid = cm.id AND cmv.userid = ?
1101 INNER JOIN {modules} m ON m.id = cm.module
1102 WHERE m.visible = 1 AND cm.course = ?",
1103 [$userid, $userid, $this->course->id]);
1104 $cminfos = get_fast_modinfo($cm->course, $userid)->get_cms();
1106 // Reindex by course module id.
1107 foreach ($alldatabycmc as $data) {
1109 // Filter acitivites with no cm_info (missing plugins or other causes).
1110 if (!isset($cminfos[$data->cmid])) {
1111 continue;
1114 if (empty($data->coursemoduleid)) {
1115 $cacheddata[$data->cmid] = $defaultdata;
1116 $cacheddata[$data->cmid]['coursemoduleid'] = $data->cmid;
1117 } else {
1118 unset($data->cmid);
1119 $cacheddata[$data->coursemoduleid] = (array) $data;
1123 if (!isset($cacheddata[$cminfo->id])) {
1124 $errormessage = "Unexpected error: course-module {$cminfo->id} could not be found on course {$this->course->id}";
1125 $this->internal_systemerror($errormessage);
1128 $data = $cacheddata[$cminfo->id];
1129 } else {
1130 // Get single record
1131 $data = $this->get_completion_data($cminfo->id, $userid, $defaultdata);
1132 // Put in cache.
1133 $cacheddata[$cminfo->id] = $data;
1136 // Fill the other completion data for this user in this module instance.
1137 $data += $this->get_other_cm_completion_data($cminfo, $userid);
1138 $data['other_cm_completion_data_fetched'] = true;
1140 // Put in cache
1141 $cacheddata[$cminfo->id] = $data;
1143 if ($usecache) {
1144 $cacheddata['cacherev'] = $this->course->cacherev;
1145 $completioncache->set($key, $cacheddata);
1148 return $returnfilteredvalue($cacheddata[$cminfo->id]);
1152 * Get the latest completion state for each criteria used in the module
1154 * @param cm_info $cm The corresponding module's information
1155 * @param int $userid The id for the user we are calculating core completion state
1156 * @return array $data The individualised core completion state used in the module.
1157 * Consists of the following keys completiongrade, passgrade, viewed
1159 public function get_core_completion_state(cm_info $cm, int $userid): array {
1160 global $DB;
1161 $data = [];
1162 // Include in the completion info the grade completion, if necessary.
1163 if (!is_null($cm->completiongradeitemnumber)) {
1164 $newstate = $this->get_grade_completion($cm, $userid);
1165 $data['completiongrade'] = $newstate;
1167 if ($cm->completionpassgrade) {
1168 // If we are asking to use pass grade completion but haven't set it properly,
1169 // then default to COMPLETION_COMPLETE_PASS.
1170 if ($newstate == COMPLETION_COMPLETE) {
1171 $newstate = COMPLETION_COMPLETE_PASS;
1174 // The activity is using 'passing grade' criteria therefore fail indication should be on this criteria.
1175 // The user has received a (failing) grade so 'completiongrade' should properly indicate this.
1176 if ($newstate == COMPLETION_COMPLETE_FAIL) {
1177 $data['completiongrade'] = COMPLETION_COMPLETE;
1180 $data['passgrade'] = $newstate;
1184 // If view is required, try and fetch from the db. In some cases, cache can be invalid.
1185 if ($cm->completionview == COMPLETION_VIEW_REQUIRED) {
1186 $data['viewed'] = COMPLETION_INCOMPLETE;
1187 $record = $DB->record_exists('course_modules_viewed', ['coursemoduleid' => $cm->id, 'userid' => $userid]);
1188 $data['viewed'] = $record ? COMPLETION_COMPLETE : COMPLETION_INCOMPLETE;
1191 return $data;
1195 * Adds the user's custom completion data on the given course module.
1197 * @param cm_info $cm The course module information.
1198 * @param int $userid The user ID.
1199 * @return array The additional completion data.
1201 protected function get_other_cm_completion_data(cm_info $cm, int $userid): array {
1202 $data = $this->get_core_completion_state($cm, $userid);
1204 // Custom activity module completion data.
1206 // Cast custom data to array before checking for custom completion rules.
1207 // We call ->get_custom_data() instead of ->customdata here because there is the chance of recursive calling,
1208 // and we cannot call a getter from a getter in PHP.
1209 $customdata = (array) $cm->get_custom_data();
1210 // Return early if the plugin does not define custom completion rules.
1211 if (empty($customdata['customcompletionrules'])) {
1212 return $data;
1215 // Return early if the activity modules doe not implement the activity_custom_completion class.
1216 $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cm->modname);
1217 if (!$cmcompletionclass) {
1218 return $data;
1221 /** @var activity_custom_completion $customcmcompletion */
1222 $customcmcompletion = new $cmcompletionclass($cm, $userid, $data);
1223 foreach ($customdata['customcompletionrules'] as $rule => $enabled) {
1224 if (!$enabled) {
1225 // Skip inactive completion rules.
1226 continue;
1228 // Get this custom completion rule's completion state.
1229 $data['customcompletion'][$rule] = $customcmcompletion->get_state($rule);
1232 return $data;
1236 * Updates completion data for a particular coursemodule and user (user is
1237 * determined from $data).
1239 * (Internal function. Not private, so we can unit-test it.)
1241 * @param stdClass|cm_info $cm Activity
1242 * @param stdClass $data Data about completion for that user
1243 * @param bool $isbulkupdate If bulk grade update is happening.
1245 public function internal_set_data($cm, $data, $isbulkupdate = false) {
1246 global $USER, $DB, $CFG;
1247 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_activity.php');
1249 $transaction = $DB->start_delegated_transaction();
1250 if (!$data->id) {
1251 // Check there isn't really a row
1252 $data->id = $DB->get_field('course_modules_completion', 'id',
1253 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1255 if (!$data->id) {
1256 // Didn't exist before, needs creating
1257 $data->id = $DB->insert_record('course_modules_completion', $data);
1258 } else {
1259 // Has real (nonzero) id meaning that a database row exists, update
1260 $DB->update_record('course_modules_completion', $data);
1262 $dataview = new stdClass();
1263 $dataview->coursemoduleid = $data->coursemoduleid;
1264 $dataview->userid = $data->userid;
1265 $dataview->id = $DB->get_field('course_modules_viewed', 'id',
1266 ['coursemoduleid' => $dataview->coursemoduleid, 'userid' => $dataview->userid]);
1267 if (!$data->viewed && $dataview->id) {
1268 $DB->delete_records('course_modules_viewed', ['id' => $dataview->id]);
1271 if (!$dataview->id && $data->viewed) {
1272 $dataview->timecreated = time();
1273 $dataview->id = $DB->insert_record('course_modules_viewed', $dataview);
1275 $transaction->allow_commit();
1277 $cmcontext = context_module::instance($data->coursemoduleid);
1279 $completioncache = cache::make('core', 'completion');
1280 $cachekey = "{$data->userid}_{$cm->course}";
1281 if ($data->userid == $USER->id) {
1282 // Fetch other completion data to cache (e.g. require grade completion status, custom completion rule statues).
1283 $cminfo = cm_info::create($cm, $data->userid); // Make sure we're working on a cm_info object.
1284 $otherdata = $this->get_other_cm_completion_data($cminfo, $data->userid);
1285 foreach ($otherdata as $key => $value) {
1286 $data->$key = $value;
1289 // Update module completion in user's cache.
1290 if (!($cachedata = $completioncache->get($cachekey))
1291 || $cachedata['cacherev'] != $this->course->cacherev) {
1292 $cachedata = array('cacherev' => $this->course->cacherev);
1294 $cachedata[$cm->id] = (array) $data;
1295 $cachedata[$cm->id]['other_cm_completion_data_fetched'] = true;
1296 $completioncache->set($cachekey, $cachedata);
1298 // reset modinfo for user (no need to call rebuild_course_cache())
1299 get_fast_modinfo($cm->course, 0, true);
1300 } else {
1301 // Remove another user's completion cache for this course.
1302 $completioncache->delete($cachekey);
1305 // For single user actions the code must reevaluate some completion state instantly, see MDL-32103.
1306 if ($isbulkupdate) {
1307 return;
1308 } else {
1309 $userdata = ['userid' => $data->userid, 'courseid' => $this->course_id];
1310 $coursecompletionid = \core_completion\api::mark_course_completions_activity_criteria($userdata);
1311 if ($coursecompletionid) {
1312 aggregate_completions($coursecompletionid);
1316 // Trigger an event for course module completion changed.
1317 $event = \core\event\course_module_completion_updated::create(array(
1318 'objectid' => $data->id,
1319 'context' => $cmcontext,
1320 'relateduserid' => $data->userid,
1321 'other' => array(
1322 'relateduserid' => $data->userid,
1323 'overrideby' => $data->overrideby,
1324 'completionstate' => $data->completionstate
1327 $event->add_record_snapshot('course_modules_completion', $data);
1328 $event->trigger();
1332 * Return whether or not the course has activities with completion enabled.
1334 * @return boolean true when there is at least one activity with completion enabled.
1336 public function has_activities() {
1337 $modinfo = get_fast_modinfo($this->course);
1338 foreach ($modinfo->get_cms() as $cm) {
1339 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1340 return true;
1343 return false;
1347 * Obtains a list of activities for which completion is enabled on the
1348 * course. The list is ordered by the section order of those activities.
1350 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1351 * empty array if none
1353 public function get_activities() {
1354 $modinfo = get_fast_modinfo($this->course);
1355 $result = array();
1356 foreach ($modinfo->get_cms() as $cm) {
1357 if ($cm->completion != COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) {
1358 $result[$cm->id] = $cm;
1361 return $result;
1365 * Checks to see if the userid supplied has a tracked role in
1366 * this course
1368 * @param int $userid User id
1369 * @return bool
1371 public function is_tracked_user($userid) {
1372 return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1376 * Returns the number of users whose progress is tracked in this course.
1378 * Optionally supply a search's where clause, or a group id.
1380 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1381 * @param array $whereparams Where clause params
1382 * @param int $groupid Group id
1383 * @return int Number of tracked users
1385 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1386 global $DB;
1388 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1389 context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1390 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1391 if ($where) {
1392 $sql .= " WHERE $where";
1395 $params = array_merge($enrolledparams, $whereparams);
1396 return $DB->count_records_sql($sql, $params);
1400 * Return array of users whose progress is tracked in this course.
1402 * Optionally supply a search's where clause, group id, sorting, paging.
1404 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1405 * @param array $whereparams Where clause params (optional)
1406 * @param int $groupid Group ID to restrict to (optional)
1407 * @param string $sort Order by clause (optional)
1408 * @param int $limitfrom Result start (optional)
1409 * @param int $limitnum Result max size (optional)
1410 * @param context $extracontext If set, includes extra user information fields
1411 * as appropriate to display for current user in this context
1412 * @return array Array of user objects with user fields (including all identity fields)
1414 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1415 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1417 global $DB;
1419 list($enrolledsql, $params) = get_enrolled_sql(
1420 context_course::instance($this->course->id),
1421 'moodle/course:isincompletionreports', $groupid, true);
1423 $userfieldsapi = \core_user\fields::for_identity($extracontext)->with_name()->excluding('id', 'idnumber');
1424 $fieldssql = $userfieldsapi->get_sql('u', true);
1425 $sql = 'SELECT u.id, u.idnumber ' . $fieldssql->selects;
1426 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1427 $sql .= $fieldssql->joins;
1428 $params = array_merge($params, $fieldssql->params);
1430 if ($where) {
1431 $sql .= " AND $where";
1432 $params = array_merge($params, $whereparams);
1435 if ($sort) {
1436 $sql .= " ORDER BY $sort";
1439 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1443 * Obtains progress information across a course for all users on that course, or
1444 * for all users in a specific group. Intended for use when displaying progress.
1446 * This includes only users who, in course context, have one of the roles for
1447 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1449 * Users are included (in the first array) even if they do not have
1450 * completion progress for any course-module.
1452 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1453 * last name
1454 * @param string $where Where clause sql (optional)
1455 * @param array $where_params Where clause params (optional)
1456 * @param int $groupid Group ID or 0 (default)/false for all groups
1457 * @param int $pagesize Number of users to actually return (optional)
1458 * @param int $start User to start at if paging (optional)
1459 * @param context $extracontext If set, includes extra user information fields
1460 * as appropriate to display for current user in this context
1461 * @return stdClass with ->total and ->start (same as $start) and ->users;
1462 * an array of user objects (like mdl_user id, firstname, lastname)
1463 * containing an additional ->progress array of coursemoduleid => completionstate
1465 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1466 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1467 global $CFG, $DB;
1469 // Get list of applicable users
1470 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1471 $start, $pagesize, $extracontext);
1473 // Get progress information for these users in groups of 1, 000 (if needed)
1474 // to avoid making the SQL IN too long
1475 $results = array();
1476 $userids = array();
1477 foreach ($users as $user) {
1478 $userids[] = $user->id;
1479 $results[$user->id] = $user;
1480 $results[$user->id]->progress = array();
1483 for($i=0; $i<count($userids); $i+=1000) {
1484 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1486 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1487 array_splice($params, 0, 0, array($this->course->id));
1488 $rs = $DB->get_recordset_sql("
1489 SELECT
1490 cmc.*
1491 FROM
1492 {course_modules} cm
1493 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1494 WHERE
1495 cm.course=? AND cmc.userid $insql", $params);
1496 foreach ($rs as $progress) {
1497 $progress = (object)$progress;
1498 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1500 $rs->close();
1503 return $results;
1507 * Called by grade code to inform the completion system when a grade has
1508 * been changed. If the changed grade is used to determine completion for
1509 * the course-module, then the completion status will be updated.
1511 * @param stdClass|cm_info $cm Course-module for item that owns grade
1512 * @param grade_item $item Grade item
1513 * @param stdClass $grade
1514 * @param bool $deleted
1515 * @param bool $isbulkupdate If bulk grade update is happening.
1517 public function inform_grade_changed($cm, $item, $grade, $deleted, $isbulkupdate = false) {
1518 // Bail out now if completion is not enabled for course-module, it is enabled
1519 // but is set to manual, grade is not used to compute completion, or this
1520 // is a different numbered grade
1521 if (!$this->is_enabled($cm) ||
1522 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1523 is_null($cm->completiongradeitemnumber) ||
1524 $item->itemnumber != $cm->completiongradeitemnumber) {
1525 return;
1528 // What is the expected result based on this grade?
1529 if ($deleted) {
1530 // Grade being deleted, so only change could be to make it incomplete
1531 $possibleresult = COMPLETION_INCOMPLETE;
1532 } else {
1533 $possibleresult = self::internal_get_grade_state($item, $grade);
1536 // OK, let's update state based on this
1537 $this->update_state($cm, $possibleresult, $grade->userid, false, $isbulkupdate);
1541 * Calculates the completion state that would result from a graded item
1542 * (where grade-based completion is turned on) based on the actual grade
1543 * and settings.
1545 * Internal function. Not private, so we can unit-test it.
1547 * @param grade_item $item an instance of grade_item
1548 * @param grade_grade $grade an instance of grade_grade
1549 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1551 public static function internal_get_grade_state($item, $grade) {
1552 // If no grade is supplied or the grade doesn't have an actual value, then
1553 // this is not complete.
1554 if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1555 return COMPLETION_INCOMPLETE;
1558 // Conditions to show pass/fail:
1559 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1560 // b) Grade is visible (neither hidden nor hidden-until)
1561 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1562 // Use final grade if set otherwise raw grade
1563 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1565 // We are displaying and tracking pass/fail
1566 if ($score >= $item->gradepass) {
1567 return COMPLETION_COMPLETE_PASS;
1568 } else {
1569 return COMPLETION_COMPLETE_FAIL;
1571 } else {
1572 // Not displaying pass/fail, so just if there is a grade
1573 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1574 // Grade exists, so maybe complete now
1575 return COMPLETION_COMPLETE;
1576 } else {
1577 // Grade does not exist, so maybe incomplete now
1578 return COMPLETION_INCOMPLETE;
1584 * Aggregate activity completion state
1586 * @param int $type Aggregation type (COMPLETION_* constant)
1587 * @param bool $old Old state
1588 * @param bool $new New state
1589 * @return bool
1591 public static function aggregate_completion_states($type, $old, $new) {
1592 if ($type == COMPLETION_AND) {
1593 return $old && $new;
1594 } else {
1595 return $old || $new;
1600 * This is to be used only for system errors (things that shouldn't happen)
1601 * and not user-level errors.
1603 * @global type $CFG
1604 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1605 * @throws moodle_exception Exception with the error string as debug info
1607 public function internal_systemerror($error) {
1608 global $CFG;
1609 throw new moodle_exception('err_system','completion',
1610 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1614 * Get completion data include viewed field.
1616 * @param int $coursemoduleid The course module id.
1617 * @param int $userid The User ID.
1618 * @param array $defaultdata Default data completion.
1619 * @return array Data completion retrieved.
1621 public function get_completion_data(int $coursemoduleid, int $userid, array $defaultdata): array {
1622 global $DB;
1624 // MySQL doesn't support FULL JOIN syntax, so we use UNION in the below SQL to help MySQL.
1625 $sql = "SELECT cmc.*, cmv.coursemoduleid as cmvcoursemoduleid, cmv.userid as cmvuserid
1626 FROM {course_modules_completion} cmc
1627 LEFT JOIN {course_modules_viewed} cmv ON cmc.coursemoduleid = cmv.coursemoduleid AND cmc.userid = cmv.userid
1628 WHERE cmc.coursemoduleid = :cmccoursemoduleid AND cmc.userid = :cmcuserid
1629 UNION
1630 SELECT cmc2.*, cmv2.coursemoduleid as cmvcoursemoduleid, cmv2.userid as cmvuserid
1631 FROM {course_modules_completion} cmc2
1632 RIGHT JOIN {course_modules_viewed} cmv2
1633 ON cmc2.coursemoduleid = cmv2.coursemoduleid AND cmc2.userid = cmv2.userid
1634 WHERE cmv2.coursemoduleid = :cmvcoursemoduleid AND cmv2.userid = :cmvuserid";
1636 $data = $DB->get_record_sql($sql, ['cmccoursemoduleid' => $coursemoduleid, 'cmcuserid' => $userid,
1637 'cmvcoursemoduleid' => $coursemoduleid, 'cmvuserid' => $userid]);
1639 if (!$data) {
1640 $data = $defaultdata;
1641 } else {
1642 if (empty($data->coursemoduleid) && empty($data->userid)) {
1643 $data->coursemoduleid = $data->cmvcoursemoduleid;
1644 $data->userid = $data->cmvuserid;
1646 unset($data->cmvcoursemoduleid);
1647 unset($data->cmvuserid);
1649 // When reseting all state in the completion, we need to keep current view state.
1650 $data->viewed = 1;
1653 return (array)$data;
1658 * Aggregate criteria status's as per configured aggregation method.
1660 * @param int $method COMPLETION_AGGREGATION_* constant.
1661 * @param bool $data Criteria completion status.
1662 * @param bool|null $state Aggregation state.
1664 function completion_cron_aggregate($method, $data, &$state) {
1665 if ($method == COMPLETION_AGGREGATION_ALL) {
1666 if ($data && $state !== false) {
1667 $state = true;
1668 } else {
1669 $state = false;
1671 } else if ($method == COMPLETION_AGGREGATION_ANY) {
1672 if ($data) {
1673 $state = true;
1674 } else if (!$data && $state === null) {
1675 $state = false;
1681 * Aggregate courses completions. This function is called when activity completion status is updated
1682 * for single user. Also when regular completion task runs it aggregates completions for all courses and users.
1684 * @param int $coursecompletionid Course completion ID to update (if 0 - update for all courses and users)
1685 * @param bool $mtraceprogress To output debug info
1686 * @since Moodle 4.0
1688 function aggregate_completions(int $coursecompletionid, bool $mtraceprogress = false) {
1689 global $DB;
1691 if (!$coursecompletionid && $mtraceprogress) {
1692 mtrace('Aggregating completions');
1694 // Save time started.
1695 $timestarted = time();
1697 // Grab all criteria and their associated criteria completions.
1698 $sql = "SELECT DISTINCT c.id AS courseid, cr.id AS criteriaid, cco.userid, cr.criteriatype, ccocr.timecompleted
1699 FROM {course_completion_criteria} cr
1700 INNER JOIN {course} c ON cr.course = c.id
1701 INNER JOIN {course_completions} cco ON cco.course = c.id
1702 LEFT JOIN {course_completion_crit_compl} ccocr
1703 ON ccocr.criteriaid = cr.id AND cco.userid = ccocr.userid
1704 WHERE c.enablecompletion = 1
1705 AND cco.timecompleted IS NULL
1706 AND cco.reaggregate > 0";
1708 if ($coursecompletionid) {
1709 $sql .= " AND cco.id = ?";
1710 $param = $coursecompletionid;
1711 } else {
1712 $sql .= " AND cco.reaggregate < ? ORDER BY courseid, cco.userid";
1713 $param = $timestarted;
1715 $rs = $DB->get_recordset_sql($sql, [$param]);
1717 // Check if result is empty.
1718 if (!$rs->valid()) {
1719 $rs->close();
1720 return;
1723 $currentuser = null;
1724 $currentcourse = null;
1725 $completions = [];
1726 while (1) {
1727 // Grab records for current user/course.
1728 foreach ($rs as $record) {
1729 // If we are still grabbing the same users completions.
1730 if ($record->userid === $currentuser && $record->courseid === $currentcourse) {
1731 $completions[$record->criteriaid] = $record;
1732 } else {
1733 break;
1737 // Aggregate.
1738 if (!empty($completions)) {
1739 if (!$coursecompletionid && $mtraceprogress) {
1740 mtrace('Aggregating completions for user ' . $currentuser . ' in course ' . $currentcourse);
1743 // Get course info object.
1744 $info = new \completion_info((object)['id' => $currentcourse]);
1746 // Setup aggregation.
1747 $overall = $info->get_aggregation_method();
1748 $activity = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ACTIVITY);
1749 $prerequisite = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_COURSE);
1750 $role = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ROLE);
1752 $overallstatus = null;
1753 $activitystatus = null;
1754 $prerequisitestatus = null;
1755 $rolestatus = null;
1757 // Get latest timecompleted.
1758 $timecompleted = null;
1760 // Check each of the criteria.
1761 foreach ($completions as $params) {
1762 $timecompleted = max($timecompleted, $params->timecompleted);
1763 $completion = new \completion_criteria_completion((array)$params, false);
1765 // Handle aggregation special cases.
1766 if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) {
1767 completion_cron_aggregate($activity, $completion->is_complete(), $activitystatus);
1768 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) {
1769 completion_cron_aggregate($prerequisite, $completion->is_complete(), $prerequisitestatus);
1770 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ROLE) {
1771 completion_cron_aggregate($role, $completion->is_complete(), $rolestatus);
1772 } else {
1773 completion_cron_aggregate($overall, $completion->is_complete(), $overallstatus);
1777 // Include role criteria aggregation in overall aggregation.
1778 if ($rolestatus !== null) {
1779 completion_cron_aggregate($overall, $rolestatus, $overallstatus);
1782 // Include activity criteria aggregation in overall aggregation.
1783 if ($activitystatus !== null) {
1784 completion_cron_aggregate($overall, $activitystatus, $overallstatus);
1787 // Include prerequisite criteria aggregation in overall aggregation.
1788 if ($prerequisitestatus !== null) {
1789 completion_cron_aggregate($overall, $prerequisitestatus, $overallstatus);
1792 // If aggregation status is true, mark course complete for user.
1793 if ($overallstatus) {
1794 if (!$coursecompletionid && $mtraceprogress) {
1795 mtrace('Marking complete');
1798 $ccompletion = new \completion_completion([
1799 'course' => $params->courseid,
1800 'userid' => $params->userid
1802 $ccompletion->mark_complete($timecompleted);
1806 // If this is the end of the recordset, break the loop.
1807 if (!$rs->valid()) {
1808 $rs->close();
1809 break;
1812 // New/next user, update user details, reset completions.
1813 $currentuser = $record->userid;
1814 $currentcourse = $record->courseid;
1815 $completions = [];
1816 $completions[$record->criteriaid] = $record;
1819 // Mark all users as aggregated.
1820 if ($coursecompletionid) {
1821 $select = "reaggregate > 0 AND id = ?";
1822 $param = $coursecompletionid;
1823 } else {
1824 $select = "reaggregate > 0 AND reaggregate < ?";
1825 $param = $timestarted;
1826 if (PHPUNIT_TEST) {
1827 // MDL-33320: for instant completions we need aggregate to work in a single run.
1828 $DB->set_field('course_completions', 'reaggregate', $timestarted - 2);
1831 $DB->set_field_select('course_completions', 'reaggregate', 0, $select, [$param]);