Automatically generated installer lang files
[moodle.git] / lib / completionlib.php
blobcd6edf242fc6e22036da93cf03f66b411baf4e2d
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 print_error('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 FROM {course_modules} cm
1096 LEFT JOIN {course_modules_completion} cmc ON cmc.coursemoduleid = cm.id
1097 AND cmc.userid = ?
1098 INNER JOIN {modules} m ON m.id = cm.module
1099 WHERE m.visible = 1 AND cm.course = ?", [$userid, $this->course->id]);
1101 $cminfos = get_fast_modinfo($cm->course, $userid)->get_cms();
1103 // Reindex by course module id.
1104 foreach ($alldatabycmc as $data) {
1106 // Filter acitivites with no cm_info (missing plugins or other causes).
1107 if (!isset($cminfos[$data->cmid])) {
1108 continue;
1111 if (empty($data->coursemoduleid)) {
1112 $cacheddata[$data->cmid] = $defaultdata;
1113 $cacheddata[$data->cmid]['coursemoduleid'] = $data->cmid;
1114 } else {
1115 unset($data->cmid);
1116 $cacheddata[$data->coursemoduleid] = (array) $data;
1120 if (!isset($cacheddata[$cminfo->id])) {
1121 $errormessage = "Unexpected error: course-module {$cminfo->id} could not be found on course {$this->course->id}";
1122 $this->internal_systemerror($errormessage);
1125 $data = $cacheddata[$cminfo->id];
1126 } else {
1127 // Get single record
1128 $data = $DB->get_record('course_modules_completion', array('coursemoduleid' => $cminfo->id, 'userid' => $userid));
1129 if ($data) {
1130 $data = (array)$data;
1131 } else {
1132 // Row not present counts as 'not complete'.
1133 $data = $defaultdata;
1136 // Put in cache.
1137 $cacheddata[$cminfo->id] = $data;
1140 // Fill the other completion data for this user in this module instance.
1141 $data += $this->get_other_cm_completion_data($cminfo, $userid);
1142 $data['other_cm_completion_data_fetched'] = true;
1144 // Put in cache
1145 $cacheddata[$cminfo->id] = $data;
1147 if ($usecache) {
1148 $cacheddata['cacherev'] = $this->course->cacherev;
1149 $completioncache->set($key, $cacheddata);
1152 return $returnfilteredvalue($cacheddata[$cminfo->id]);
1156 * Get the latest completion state for each criteria used in the module
1158 * @param cm_info $cm The corresponding module's information
1159 * @param int $userid The id for the user we are calculating core completion state
1160 * @return array $data The individualised core completion state used in the module.
1161 * Consists of the following keys completiongrade, passgrade, viewed
1163 public function get_core_completion_state(cm_info $cm, int $userid): array {
1164 global $DB;
1165 $data = [];
1166 // Include in the completion info the grade completion, if necessary.
1167 if (!is_null($cm->completiongradeitemnumber)) {
1168 $newstate = $this->get_grade_completion($cm, $userid);
1169 $data['completiongrade'] = $newstate;
1171 if ($cm->completionpassgrade) {
1172 // If we are asking to use pass grade completion but haven't set it properly,
1173 // then default to COMPLETION_COMPLETE_PASS.
1174 if ($newstate == COMPLETION_COMPLETE) {
1175 $newstate = COMPLETION_COMPLETE_PASS;
1178 // The activity is using 'passing grade' criteria therefore fail indication should be on this criteria.
1179 // The user has received a (failing) grade so 'completiongrade' should properly indicate this.
1180 if ($newstate == COMPLETION_COMPLETE_FAIL) {
1181 $data['completiongrade'] = COMPLETION_COMPLETE;
1184 $data['passgrade'] = $newstate;
1188 // If view is required, try and fetch from the db. In some cases, cache can be invalid.
1189 if ($cm->completionview == COMPLETION_VIEW_REQUIRED) {
1190 $data['viewed'] = COMPLETION_INCOMPLETE;
1191 $record = $DB->get_record('course_modules_completion', array('coursemoduleid' => $cm->id, 'userid' => $userid));
1192 if ($record) {
1193 $data['viewed'] = ($record->viewed == COMPLETION_VIEWED ? COMPLETION_COMPLETE : COMPLETION_INCOMPLETE);
1197 return $data;
1201 * Adds the user's custom completion data on the given course module.
1203 * @param cm_info $cm The course module information.
1204 * @param int $userid The user ID.
1205 * @return array The additional completion data.
1207 protected function get_other_cm_completion_data(cm_info $cm, int $userid): array {
1208 $data = $this->get_core_completion_state($cm, $userid);
1210 // Custom activity module completion data.
1212 // Cast custom data to array before checking for custom completion rules.
1213 // We call ->get_custom_data() instead of ->customdata here because there is the chance of recursive calling,
1214 // and we cannot call a getter from a getter in PHP.
1215 $customdata = (array) $cm->get_custom_data();
1216 // Return early if the plugin does not define custom completion rules.
1217 if (empty($customdata['customcompletionrules'])) {
1218 return $data;
1221 // Return early if the activity modules doe not implement the activity_custom_completion class.
1222 $cmcompletionclass = activity_custom_completion::get_cm_completion_class($cm->modname);
1223 if (!$cmcompletionclass) {
1224 return $data;
1227 /** @var activity_custom_completion $customcmcompletion */
1228 $customcmcompletion = new $cmcompletionclass($cm, $userid, $data);
1229 foreach ($customdata['customcompletionrules'] as $rule => $enabled) {
1230 if (!$enabled) {
1231 // Skip inactive completion rules.
1232 continue;
1234 // Get this custom completion rule's completion state.
1235 $data['customcompletion'][$rule] = $customcmcompletion->get_state($rule);
1238 return $data;
1242 * Updates completion data for a particular coursemodule and user (user is
1243 * determined from $data).
1245 * (Internal function. Not private, so we can unit-test it.)
1247 * @param stdClass|cm_info $cm Activity
1248 * @param stdClass $data Data about completion for that user
1249 * @param bool $isbulkupdate If bulk grade update is happening.
1251 public function internal_set_data($cm, $data, $isbulkupdate = false) {
1252 global $USER, $DB, $CFG;
1253 require_once($CFG->dirroot.'/completion/criteria/completion_criteria_activity.php');
1255 $transaction = $DB->start_delegated_transaction();
1256 if (!$data->id) {
1257 // Check there isn't really a row
1258 $data->id = $DB->get_field('course_modules_completion', 'id',
1259 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1261 if (!$data->id) {
1262 // Didn't exist before, needs creating
1263 $data->id = $DB->insert_record('course_modules_completion', $data);
1264 } else {
1265 // Has real (nonzero) id meaning that a database row exists, update
1266 $DB->update_record('course_modules_completion', $data);
1268 $transaction->allow_commit();
1270 $cmcontext = context_module::instance($data->coursemoduleid);
1272 $completioncache = cache::make('core', 'completion');
1273 $cachekey = "{$data->userid}_{$cm->course}";
1274 if ($data->userid == $USER->id) {
1275 // Fetch other completion data to cache (e.g. require grade completion status, custom completion rule statues).
1276 $cminfo = cm_info::create($cm, $data->userid); // Make sure we're working on a cm_info object.
1277 $otherdata = $this->get_other_cm_completion_data($cminfo, $data->userid);
1278 foreach ($otherdata as $key => $value) {
1279 $data->$key = $value;
1282 // Update module completion in user's cache.
1283 if (!($cachedata = $completioncache->get($cachekey))
1284 || $cachedata['cacherev'] != $this->course->cacherev) {
1285 $cachedata = array('cacherev' => $this->course->cacherev);
1287 $cachedata[$cm->id] = (array) $data;
1288 $cachedata[$cm->id]['other_cm_completion_data_fetched'] = true;
1289 $completioncache->set($cachekey, $cachedata);
1291 // reset modinfo for user (no need to call rebuild_course_cache())
1292 get_fast_modinfo($cm->course, 0, true);
1293 } else {
1294 // Remove another user's completion cache for this course.
1295 $completioncache->delete($cachekey);
1298 // For single user actions the code must reevaluate some completion state instantly, see MDL-32103.
1299 if ($isbulkupdate) {
1300 return;
1301 } else {
1302 $userdata = ['userid' => $data->userid, 'courseid' => $this->course_id];
1303 $coursecompletionid = \core_completion\api::mark_course_completions_activity_criteria($userdata);
1304 if ($coursecompletionid) {
1305 aggregate_completions($coursecompletionid);
1309 // Trigger an event for course module completion changed.
1310 $event = \core\event\course_module_completion_updated::create(array(
1311 'objectid' => $data->id,
1312 'context' => $cmcontext,
1313 'relateduserid' => $data->userid,
1314 'other' => array(
1315 'relateduserid' => $data->userid,
1316 'overrideby' => $data->overrideby,
1317 'completionstate' => $data->completionstate
1320 $event->add_record_snapshot('course_modules_completion', $data);
1321 $event->trigger();
1325 * Return whether or not the course has activities with completion enabled.
1327 * @return boolean true when there is at least one activity with completion enabled.
1329 public function has_activities() {
1330 $modinfo = get_fast_modinfo($this->course);
1331 foreach ($modinfo->get_cms() as $cm) {
1332 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1333 return true;
1336 return false;
1340 * Obtains a list of activities for which completion is enabled on the
1341 * course. The list is ordered by the section order of those activities.
1343 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1344 * empty array if none
1346 public function get_activities() {
1347 $modinfo = get_fast_modinfo($this->course);
1348 $result = array();
1349 foreach ($modinfo->get_cms() as $cm) {
1350 if ($cm->completion != COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) {
1351 $result[$cm->id] = $cm;
1354 return $result;
1358 * Checks to see if the userid supplied has a tracked role in
1359 * this course
1361 * @param int $userid User id
1362 * @return bool
1364 public function is_tracked_user($userid) {
1365 return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1369 * Returns the number of users whose progress is tracked in this course.
1371 * Optionally supply a search's where clause, or a group id.
1373 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1374 * @param array $whereparams Where clause params
1375 * @param int $groupid Group id
1376 * @return int Number of tracked users
1378 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1379 global $DB;
1381 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1382 context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1383 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1384 if ($where) {
1385 $sql .= " WHERE $where";
1388 $params = array_merge($enrolledparams, $whereparams);
1389 return $DB->count_records_sql($sql, $params);
1393 * Return array of users whose progress is tracked in this course.
1395 * Optionally supply a search's where clause, group id, sorting, paging.
1397 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1398 * @param array $whereparams Where clause params (optional)
1399 * @param int $groupid Group ID to restrict to (optional)
1400 * @param string $sort Order by clause (optional)
1401 * @param int $limitfrom Result start (optional)
1402 * @param int $limitnum Result max size (optional)
1403 * @param context $extracontext If set, includes extra user information fields
1404 * as appropriate to display for current user in this context
1405 * @return array Array of user objects with user fields (including all identity fields)
1407 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1408 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1410 global $DB;
1412 list($enrolledsql, $params) = get_enrolled_sql(
1413 context_course::instance($this->course->id),
1414 'moodle/course:isincompletionreports', $groupid, true);
1416 $userfieldsapi = \core_user\fields::for_identity($extracontext)->with_name()->excluding('id', 'idnumber');
1417 $fieldssql = $userfieldsapi->get_sql('u', true);
1418 $sql = 'SELECT u.id, u.idnumber ' . $fieldssql->selects;
1419 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1420 $sql .= $fieldssql->joins;
1421 $params = array_merge($params, $fieldssql->params);
1423 if ($where) {
1424 $sql .= " AND $where";
1425 $params = array_merge($params, $whereparams);
1428 if ($sort) {
1429 $sql .= " ORDER BY $sort";
1432 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1436 * Obtains progress information across a course for all users on that course, or
1437 * for all users in a specific group. Intended for use when displaying progress.
1439 * This includes only users who, in course context, have one of the roles for
1440 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1442 * Users are included (in the first array) even if they do not have
1443 * completion progress for any course-module.
1445 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1446 * last name
1447 * @param string $where Where clause sql (optional)
1448 * @param array $where_params Where clause params (optional)
1449 * @param int $groupid Group ID or 0 (default)/false for all groups
1450 * @param int $pagesize Number of users to actually return (optional)
1451 * @param int $start User to start at if paging (optional)
1452 * @param context $extracontext If set, includes extra user information fields
1453 * as appropriate to display for current user in this context
1454 * @return stdClass with ->total and ->start (same as $start) and ->users;
1455 * an array of user objects (like mdl_user id, firstname, lastname)
1456 * containing an additional ->progress array of coursemoduleid => completionstate
1458 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1459 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1460 global $CFG, $DB;
1462 // Get list of applicable users
1463 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1464 $start, $pagesize, $extracontext);
1466 // Get progress information for these users in groups of 1, 000 (if needed)
1467 // to avoid making the SQL IN too long
1468 $results = array();
1469 $userids = array();
1470 foreach ($users as $user) {
1471 $userids[] = $user->id;
1472 $results[$user->id] = $user;
1473 $results[$user->id]->progress = array();
1476 for($i=0; $i<count($userids); $i+=1000) {
1477 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1479 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1480 array_splice($params, 0, 0, array($this->course->id));
1481 $rs = $DB->get_recordset_sql("
1482 SELECT
1483 cmc.*
1484 FROM
1485 {course_modules} cm
1486 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1487 WHERE
1488 cm.course=? AND cmc.userid $insql", $params);
1489 foreach ($rs as $progress) {
1490 $progress = (object)$progress;
1491 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1493 $rs->close();
1496 return $results;
1500 * Called by grade code to inform the completion system when a grade has
1501 * been changed. If the changed grade is used to determine completion for
1502 * the course-module, then the completion status will be updated.
1504 * @param stdClass|cm_info $cm Course-module for item that owns grade
1505 * @param grade_item $item Grade item
1506 * @param stdClass $grade
1507 * @param bool $deleted
1508 * @param bool $isbulkupdate If bulk grade update is happening.
1510 public function inform_grade_changed($cm, $item, $grade, $deleted, $isbulkupdate = false) {
1511 // Bail out now if completion is not enabled for course-module, it is enabled
1512 // but is set to manual, grade is not used to compute completion, or this
1513 // is a different numbered grade
1514 if (!$this->is_enabled($cm) ||
1515 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1516 is_null($cm->completiongradeitemnumber) ||
1517 $item->itemnumber != $cm->completiongradeitemnumber) {
1518 return;
1521 // What is the expected result based on this grade?
1522 if ($deleted) {
1523 // Grade being deleted, so only change could be to make it incomplete
1524 $possibleresult = COMPLETION_INCOMPLETE;
1525 } else {
1526 $possibleresult = self::internal_get_grade_state($item, $grade);
1529 // OK, let's update state based on this
1530 $this->update_state($cm, $possibleresult, $grade->userid, false, $isbulkupdate);
1534 * Calculates the completion state that would result from a graded item
1535 * (where grade-based completion is turned on) based on the actual grade
1536 * and settings.
1538 * Internal function. Not private, so we can unit-test it.
1540 * @param grade_item $item an instance of grade_item
1541 * @param grade_grade $grade an instance of grade_grade
1542 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1544 public static function internal_get_grade_state($item, $grade) {
1545 // If no grade is supplied or the grade doesn't have an actual value, then
1546 // this is not complete.
1547 if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1548 return COMPLETION_INCOMPLETE;
1551 // Conditions to show pass/fail:
1552 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1553 // b) Grade is visible (neither hidden nor hidden-until)
1554 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1555 // Use final grade if set otherwise raw grade
1556 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1558 // We are displaying and tracking pass/fail
1559 if ($score >= $item->gradepass) {
1560 return COMPLETION_COMPLETE_PASS;
1561 } else {
1562 return COMPLETION_COMPLETE_FAIL;
1564 } else {
1565 // Not displaying pass/fail, so just if there is a grade
1566 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1567 // Grade exists, so maybe complete now
1568 return COMPLETION_COMPLETE;
1569 } else {
1570 // Grade does not exist, so maybe incomplete now
1571 return COMPLETION_INCOMPLETE;
1577 * Aggregate activity completion state
1579 * @param int $type Aggregation type (COMPLETION_* constant)
1580 * @param bool $old Old state
1581 * @param bool $new New state
1582 * @return bool
1584 public static function aggregate_completion_states($type, $old, $new) {
1585 if ($type == COMPLETION_AND) {
1586 return $old && $new;
1587 } else {
1588 return $old || $new;
1593 * This is to be used only for system errors (things that shouldn't happen)
1594 * and not user-level errors.
1596 * @global type $CFG
1597 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1598 * @throws moodle_exception Exception with the error string as debug info
1600 public function internal_systemerror($error) {
1601 global $CFG;
1602 throw new moodle_exception('err_system','completion',
1603 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1608 * Aggregate criteria status's as per configured aggregation method.
1610 * @param int $method COMPLETION_AGGREGATION_* constant.
1611 * @param bool $data Criteria completion status.
1612 * @param bool|null $state Aggregation state.
1614 function completion_cron_aggregate($method, $data, &$state) {
1615 if ($method == COMPLETION_AGGREGATION_ALL) {
1616 if ($data && $state !== false) {
1617 $state = true;
1618 } else {
1619 $state = false;
1621 } else if ($method == COMPLETION_AGGREGATION_ANY) {
1622 if ($data) {
1623 $state = true;
1624 } else if (!$data && $state === null) {
1625 $state = false;
1631 * Aggregate courses completions. This function is called when activity completion status is updated
1632 * for single user. Also when regular completion task runs it aggregates completions for all courses and users.
1634 * @param int $coursecompletionid Course completion ID to update (if 0 - update for all courses and users)
1635 * @param bool $mtraceprogress To output debug info
1636 * @since Moodle 4.0
1638 function aggregate_completions(int $coursecompletionid, bool $mtraceprogress = false) {
1639 global $DB;
1641 if (!$coursecompletionid && $mtraceprogress) {
1642 mtrace('Aggregating completions');
1644 // Save time started.
1645 $timestarted = time();
1647 // Grab all criteria and their associated criteria completions.
1648 $sql = "SELECT DISTINCT c.id AS courseid, cr.id AS criteriaid, cco.userid, cr.criteriatype, ccocr.timecompleted
1649 FROM {course_completion_criteria} cr
1650 INNER JOIN {course} c ON cr.course = c.id
1651 INNER JOIN {course_completions} cco ON cco.course = c.id
1652 LEFT JOIN {course_completion_crit_compl} ccocr
1653 ON ccocr.criteriaid = cr.id AND cco.userid = ccocr.userid
1654 WHERE c.enablecompletion = 1
1655 AND cco.timecompleted IS NULL
1656 AND cco.reaggregate > 0";
1658 if ($coursecompletionid) {
1659 $sql .= " AND cco.id = ?";
1660 $param = $coursecompletionid;
1661 } else {
1662 $sql .= " AND cco.reaggregate < ? ORDER BY courseid, cco.userid";
1663 $param = $timestarted;
1665 $rs = $DB->get_recordset_sql($sql, [$param]);
1667 // Check if result is empty.
1668 if (!$rs->valid()) {
1669 $rs->close();
1670 return;
1673 $currentuser = null;
1674 $currentcourse = null;
1675 $completions = [];
1676 while (1) {
1677 // Grab records for current user/course.
1678 foreach ($rs as $record) {
1679 // If we are still grabbing the same users completions.
1680 if ($record->userid === $currentuser && $record->courseid === $currentcourse) {
1681 $completions[$record->criteriaid] = $record;
1682 } else {
1683 break;
1687 // Aggregate.
1688 if (!empty($completions)) {
1689 if (!$coursecompletionid && $mtraceprogress) {
1690 mtrace('Aggregating completions for user ' . $currentuser . ' in course ' . $currentcourse);
1693 // Get course info object.
1694 $info = new \completion_info((object)['id' => $currentcourse]);
1696 // Setup aggregation.
1697 $overall = $info->get_aggregation_method();
1698 $activity = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ACTIVITY);
1699 $prerequisite = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_COURSE);
1700 $role = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ROLE);
1702 $overallstatus = null;
1703 $activitystatus = null;
1704 $prerequisitestatus = null;
1705 $rolestatus = null;
1707 // Get latest timecompleted.
1708 $timecompleted = null;
1710 // Check each of the criteria.
1711 foreach ($completions as $params) {
1712 $timecompleted = max($timecompleted, $params->timecompleted);
1713 $completion = new \completion_criteria_completion((array)$params, false);
1715 // Handle aggregation special cases.
1716 if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) {
1717 completion_cron_aggregate($activity, $completion->is_complete(), $activitystatus);
1718 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) {
1719 completion_cron_aggregate($prerequisite, $completion->is_complete(), $prerequisitestatus);
1720 } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ROLE) {
1721 completion_cron_aggregate($role, $completion->is_complete(), $rolestatus);
1722 } else {
1723 completion_cron_aggregate($overall, $completion->is_complete(), $overallstatus);
1727 // Include role criteria aggregation in overall aggregation.
1728 if ($rolestatus !== null) {
1729 completion_cron_aggregate($overall, $rolestatus, $overallstatus);
1732 // Include activity criteria aggregation in overall aggregation.
1733 if ($activitystatus !== null) {
1734 completion_cron_aggregate($overall, $activitystatus, $overallstatus);
1737 // Include prerequisite criteria aggregation in overall aggregation.
1738 if ($prerequisitestatus !== null) {
1739 completion_cron_aggregate($overall, $prerequisitestatus, $overallstatus);
1742 // If aggregation status is true, mark course complete for user.
1743 if ($overallstatus) {
1744 if (!$coursecompletionid && $mtraceprogress) {
1745 mtrace('Marking complete');
1748 $ccompletion = new \completion_completion([
1749 'course' => $params->courseid,
1750 'userid' => $params->userid
1752 $ccompletion->mark_complete($timecompleted);
1756 // If this is the end of the recordset, break the loop.
1757 if (!$rs->valid()) {
1758 $rs->close();
1759 break;
1762 // New/next user, update user details, reset completions.
1763 $currentuser = $record->userid;
1764 $currentcourse = $record->courseid;
1765 $completions = [];
1766 $completions[$record->criteriaid] = $record;
1769 // Mark all users as aggregated.
1770 if ($coursecompletionid) {
1771 $select = "reaggregate > 0 AND id = ?";
1772 $param = $coursecompletionid;
1773 } else {
1774 $select = "reaggregate > 0 AND reaggregate < ?";
1775 $param = $timestarted;
1776 if (PHPUNIT_TEST) {
1777 // MDL-33320: for instant completions we need aggregate to work in a single run.
1778 $DB->set_field('course_completions', 'reaggregate', $timestarted - 2);
1781 $DB->set_field_select('course_completions', 'reaggregate', 0, $select, [$param]);