2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Contains classes, functions and constants used during the tracking
19 * of activity completion for users.
21 * Completion top-level options (admin setting enablecompletion)
23 * @package core_completion
24 * @category completion
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 use core_completion\activity_custom_completion
;
31 defined('MOODLE_INTERNAL') ||
die();
34 * Include the required completion libraries
36 require_once $CFG->dirroot
.'/completion/completion_aggregation.php';
37 require_once $CFG->dirroot
.'/completion/criteria/completion_criteria.php';
38 require_once $CFG->dirroot
.'/completion/completion_completion.php';
39 require_once $CFG->dirroot
.'/completion/completion_criteria_completion.php';
43 * The completion system is enabled in this site/course
45 define('COMPLETION_ENABLED', 1);
47 * The completion system is not enabled in this site/course
49 define('COMPLETION_DISABLED', 0);
52 * Completion tracking is disabled for this activity
53 * This is a completion tracking option per-activity (course_modules/completion)
55 define('COMPLETION_TRACKING_NONE', 0);
58 * Manual completion tracking (user ticks box) is enabled for this activity
59 * This is a completion tracking option per-activity (course_modules/completion)
61 define('COMPLETION_TRACKING_MANUAL', 1);
63 * Automatic completion tracking (system ticks box) is enabled for this activity
64 * This is a completion tracking option per-activity (course_modules/completion)
66 define('COMPLETION_TRACKING_AUTOMATIC', 2);
69 * The user has not completed this activity.
70 * This is a completion state value (course_modules_completion/completionstate)
72 define('COMPLETION_INCOMPLETE', 0);
74 * The user has completed this activity. It is not specified whether they have
75 * passed or failed it.
76 * This is a completion state value (course_modules_completion/completionstate)
78 define('COMPLETION_COMPLETE', 1);
80 * The user has completed this activity with a grade above the pass mark.
81 * This is a completion state value (course_modules_completion/completionstate)
83 define('COMPLETION_COMPLETE_PASS', 2);
85 * The user has completed this activity but their grade is less than the pass mark
86 * This is a completion state value (course_modules_completion/completionstate)
88 define('COMPLETION_COMPLETE_FAIL', 3);
91 * The effect of this change to completion status is unknown.
92 * A completion effect changes (used only in update_state)
94 define('COMPLETION_UNKNOWN', -1);
96 * The user's grade has changed, so their new state might be
97 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
98 * A completion effect changes (used only in update_state)
100 define('COMPLETION_GRADECHANGE', -2);
103 * User must view this activity.
104 * Whether view is required to create an activity (course_modules/completionview)
106 define('COMPLETION_VIEW_REQUIRED', 1);
108 * User does not need to view this activity
109 * Whether view is required to create an activity (course_modules/completionview)
111 define('COMPLETION_VIEW_NOT_REQUIRED', 0);
114 * User has viewed this activity.
115 * Completion viewed state (course_modules_completion/viewed)
117 define('COMPLETION_VIEWED', 1);
119 * User has not viewed this activity.
120 * Completion viewed state (course_modules_completion/viewed)
122 define('COMPLETION_NOT_VIEWED', 0);
125 * Completion details should be ORed together and you should return false if
128 define('COMPLETION_OR', false);
130 * Completion details should be ANDed together and you should return true if
133 define('COMPLETION_AND', true);
136 * Course completion criteria aggregation method.
138 define('COMPLETION_AGGREGATION_ALL', 1);
140 * Course completion criteria aggregation method.
142 define('COMPLETION_AGGREGATION_ANY', 2);
145 * Completion conditions will be displayed to user.
147 define('COMPLETION_SHOW_CONDITIONS', 1);
150 * Completion conditions will be hidden from user.
152 define('COMPLETION_HIDE_CONDITIONS', 0);
155 * Utility function for checking if the logged in user can view
156 * another's completion data for a particular course
159 * @param int $userid Completion data's owner
160 * @param mixed $course Course object or Course ID (optional)
163 function completion_can_view_data($userid, $course = null) {
170 if (!is_object($course)) {
172 $course = new stdClass();
176 // Check if this is the site course
177 if ($course->id
== SITEID
) {
181 // Check if completion is enabled
183 $cinfo = new completion_info($course);
184 if (!$cinfo->is_enabled()) {
188 if (!completion_info
::is_enabled_for_site()) {
193 // Is own user's data?
194 if ($USER->id
== $userid) {
198 // Check capabilities
199 $personalcontext = context_user
::instance($userid);
201 if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
203 } elseif (has_capability('report/completion:view', $personalcontext)) {
208 $coursecontext = context_course
::instance($course->id
);
210 $coursecontext = context_system
::instance();
213 if (has_capability('report/completion:view', $coursecontext)) {
222 * Class represents completion information for a course.
224 * Does not contain any data, so you can safely construct it multiple times
225 * without causing any problems.
228 * @category completion
229 * @copyright 2008 Sam Marshall
230 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
232 class completion_info
{
234 /* @var stdClass Course object passed during construction */
237 /* @var int Course id */
240 /* @var array Completion criteria {@link completion_info::get_criteria()} */
244 * Return array of aggregation methods
247 public static function get_aggregation_methods() {
249 COMPLETION_AGGREGATION_ALL
=> get_string('all'),
250 COMPLETION_AGGREGATION_ANY
=> get_string('any', 'completion'),
255 * Constructs with course details.
257 * When instantiating a new completion info object you must provide a course
258 * object with at least id, and enablecompletion properties. Property
259 * cacherev is needed if you check completion of the current user since
260 * it is used for cache validation.
262 * @param stdClass $course Moodle course object.
264 public function __construct($course) {
265 $this->course
= $course;
266 $this->course_id
= $course->id
;
270 * Determines whether completion is enabled across entire site.
272 * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
273 * COMPLETION_DISABLED (false) if it's complete
275 public static function is_enabled_for_site() {
277 return !empty($CFG->enablecompletion
);
281 * Checks whether completion is enabled in a particular course and possibly
284 * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
285 * completion enable state.
286 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
287 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
288 * for a course-module.
290 public function is_enabled($cm = null) {
293 // First check global completion
294 if (!isset($CFG->enablecompletion
) ||
$CFG->enablecompletion
== COMPLETION_DISABLED
) {
295 return COMPLETION_DISABLED
;
298 // Load data if we do not have enough
299 if (!isset($this->course
->enablecompletion
)) {
300 $this->course
= get_course($this->course_id
);
303 // Check course completion
304 if ($this->course
->enablecompletion
== COMPLETION_DISABLED
) {
305 return COMPLETION_DISABLED
;
308 // If there was no $cm and we got this far, then it's enabled
310 return COMPLETION_ENABLED
;
313 // Return course-module completion value
314 return $cm->completion
;
318 * Displays the 'Your progress' help icon, if completion tracking is enabled.
319 * Just prints the result of display_help_icon().
321 * @deprecated since Moodle 2.0 - Use display_help_icon instead.
323 public function print_help_icon() {
324 debugging('The function print_help_icon() is deprecated, please do not use it anymore.',
326 print $this->display_help_icon();
330 * Returns the 'Your progress' help icon, if completion tracking is enabled.
332 * @return string HTML code for help icon, or blank if not needed
333 * @deprecated since Moodle 4.0 - The 'Your progress' info isn't displayed any more.
335 public function display_help_icon() {
336 global $PAGE, $OUTPUT, $USER;
337 debugging('The function display_help_icon() is deprecated, please do not use it anymore.',
340 if ($this->is_enabled() && !$PAGE->user_is_editing() && $this->is_tracked_user($USER->id
) && isloggedin() &&
342 $result .= html_writer
::tag('div', get_string('yourprogress','completion') .
343 $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
344 'class' => 'completionprogress'));
350 * Get a course completion for a user
352 * @param int $user_id User id
353 * @param int $criteriatype Specific criteria type to return
354 * @return bool|completion_criteria_completion returns false on fail
356 public function get_completion($user_id, $criteriatype) {
357 $completions = $this->get_completions($user_id, $criteriatype);
359 if (empty($completions)) {
361 } elseif (count($completions) > 1) {
362 print_error('multipleselfcompletioncriteria', 'completion');
365 return $completions[0];
369 * Get all course criteria's completion objects for a user
371 * @param int $user_id User id
372 * @param int $criteriatype Specific criteria type to return (optional)
375 public function get_completions($user_id, $criteriatype = null) {
376 $criteria = $this->get_criteria($criteriatype);
378 $completions = array();
380 foreach ($criteria as $criterion) {
382 'course' => $this->course_id
,
383 'userid' => $user_id,
384 'criteriaid' => $criterion->id
387 $completion = new completion_criteria_completion($params);
388 $completion->attach_criteria($criterion);
390 $completions[] = $completion;
397 * Get completion object for a user and a criteria
399 * @param int $user_id User id
400 * @param completion_criteria $criteria Criteria object
401 * @return completion_criteria_completion
403 public function get_user_completion($user_id, $criteria) {
405 'course' => $this->course_id
,
406 'userid' => $user_id,
407 'criteriaid' => $criteria->id
,
410 $completion = new completion_criteria_completion($params);
415 * Check if course has completion criteria set
417 * @return bool Returns true if there are criteria
419 public function has_criteria() {
420 $criteria = $this->get_criteria();
422 return (bool) count($criteria);
426 * Get course completion criteria
428 * @param int $criteriatype Specific criteria type to return (optional)
430 public function get_criteria($criteriatype = null) {
432 // Fill cache if empty
433 if (!is_array($this->criteria
)) {
437 'course' => $this->course
->id
440 // Load criteria from database
441 $records = (array)$DB->get_records('course_completion_criteria', $params);
443 // Order records so activities are in the same order as they appear on the course view page.
445 $activitiesorder = array_keys(get_fast_modinfo($this->course
)->get_cms());
446 usort($records, function ($a, $b) use ($activitiesorder) {
447 $aidx = ($a->criteriatype
== COMPLETION_CRITERIA_TYPE_ACTIVITY
) ?
448 array_search($a->moduleinstance
, $activitiesorder) : false;
449 $bidx = ($b->criteriatype
== COMPLETION_CRITERIA_TYPE_ACTIVITY
) ?
450 array_search($b->moduleinstance
, $activitiesorder) : false;
451 if ($aidx === false ||
$bidx === false ||
$aidx == $bidx) {
454 return ($aidx < $bidx) ?
-1 : 1;
458 // Build array of criteria objects
459 $this->criteria
= array();
460 foreach ($records as $record) {
461 $this->criteria
[$record->id
] = completion_criteria
::factory((array)$record);
465 // If after all criteria
466 if ($criteriatype === null) {
467 return $this->criteria
;
470 // If we are only after a specific criteria type
472 foreach ($this->criteria
as $criterion) {
474 if ($criterion->criteriatype
!= $criteriatype) {
478 $criteria[$criterion->id
] = $criterion;
485 * Get aggregation method
487 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
488 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
490 public function get_aggregation_method($criteriatype = null) {
492 'course' => $this->course_id
,
493 'criteriatype' => $criteriatype
496 $aggregation = new completion_aggregation($params);
498 if (!$aggregation->id
) {
499 $aggregation->method
= COMPLETION_AGGREGATION_ALL
;
502 return $aggregation->method
;
506 * @deprecated since Moodle 2.8 MDL-46290.
508 public function get_incomplete_criteria() {
509 throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
513 * Clear old course completion criteria
515 public function clear_criteria() {
518 // Remove completion criteria records for the course itself, and any records that refer to the course.
519 $select = 'course = :course OR (criteriatype = :type AND courseinstance = :courseinstance)';
521 'course' => $this->course_id
,
522 'type' => COMPLETION_CRITERIA_TYPE_COURSE
,
523 'courseinstance' => $this->course_id
,
526 $DB->delete_records_select('course_completion_criteria', $select, $params);
527 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id
));
529 $this->delete_course_completion_data();
533 * Has the supplied user completed this course
535 * @param int $user_id User's id
538 public function is_course_complete($user_id) {
540 'userid' => $user_id,
541 'course' => $this->course_id
544 $ccompletion = new completion_completion($params);
545 return $ccompletion->is_complete();
549 * Check whether the supplied user can override the activity completion statuses within the current course.
551 * @param stdClass $user The user object.
552 * @return bool True if the user can override, false otherwise.
554 public function user_can_override_completion($user) {
555 return has_capability('moodle/course:overridecompletion', context_course
::instance($this->course_id
), $user);
559 * Updates (if necessary) the completion state of activity $cm for the given
562 * For manual completion, this function is called when completion is toggled
563 * with $possibleresult set to the target state.
565 * For automatic completion, this function should be called every time a module
566 * does something which might influence a user's completion state. For example,
567 * if a forum provides options for marking itself 'completed' once a user makes
568 * N posts, this function should be called every time a user makes a new post.
569 * [After the post has been saved to the database]. When calling, you do not
570 * need to pass in the new completion state. Instead this function carries out completion
571 * calculation by checking grades and viewed state itself, and calling the involved module
572 * via mod_{modulename}\\completion\\custom_completion::get_overall_completion_state() to
573 * check module-specific conditions.
575 * @param stdClass|cm_info $cm Course-module
576 * @param int $possibleresult Expected completion result. If the event that
577 * has just occurred (e.g. add post) can only result in making the activity
578 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
579 * has just occurred (e.g. delete post) can only result in making the activity
580 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
581 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
582 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
583 * processing early if the user's completion state already matches the expected
584 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
585 * must be used; these directly set the specified state.
586 * @param int $userid User ID to be updated. Default 0 = current user
587 * @param bool $override Whether manually overriding the existing completion state.
588 * @param bool $isbulkupdate If bulk grade update is happening.
590 * @throws moodle_exception if trying to override without permission.
592 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN
, $userid=0,
593 $override = false, $isbulkupdate = false) {
596 // Do nothing if completion is not enabled for that activity
597 if (!$this->is_enabled($cm)) {
601 // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
603 if (!$this->user_can_override_completion($USER)) {
604 throw new required_capability_exception(context_course
::instance($this->course_id
),
605 'moodle/course:overridecompletion', 'nopermission', '');
609 // Default to current user if one is not provided.
614 // Delete the cm's cached completion data for this user if automatic completion is enabled.
615 // This ensures any changes to the status of individual completion conditions in the activity will be fetched.
616 if ($cm->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
617 $completioncache = cache
::make('core', 'completion');
618 $completionkey = $userid . '_' . $this->course
->id
;
619 $completiondata = $completioncache->get($completionkey);
621 if ($completiondata !== false) {
622 unset($completiondata[$cm->id
]);
623 $completioncache->set($completionkey, $completiondata);
627 // Get current value of completion state and do nothing if it's same as
628 // the possible result of this change. If the change is to COMPLETE and the
629 // current value is one of the COMPLETE_xx subtypes, ignore that as well
630 $current = $this->get_data($cm, false, $userid);
631 if ($possibleresult == $current->completionstate ||
632 ($possibleresult == COMPLETION_COMPLETE
&&
633 ($current->completionstate
== COMPLETION_COMPLETE_PASS ||
634 $current->completionstate
== COMPLETION_COMPLETE_FAIL
))) {
638 // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
639 // unless processing another override.
640 // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
641 // overridden to INCOMPLETE to still be processed by normal completion triggers.
642 if ($cm->completion
== COMPLETION_TRACKING_AUTOMATIC
&& !is_null($current->overrideby
)
643 && $current->completionstate
== COMPLETION_COMPLETE
&& !$override) {
647 // For manual tracking, or if overriding the completion state, we set the state directly.
648 if ($cm->completion
== COMPLETION_TRACKING_MANUAL ||
$override) {
649 switch($possibleresult) {
650 case COMPLETION_COMPLETE
:
651 case COMPLETION_INCOMPLETE
:
652 $newstate = $possibleresult;
655 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
659 $newstate = $this->internal_get_state($cm, $userid, $current);
662 // If the overall completion state has changed, update it in the cache.
663 if ($newstate != $current->completionstate
) {
664 $current->completionstate
= $newstate;
665 $current->timemodified
= time();
666 $current->overrideby
= $override ?
$USER->id
: null;
667 $this->internal_set_data($cm, $current, $isbulkupdate);
672 * Calculates the completion state for an activity and user.
674 * Internal function. Not private, so we can unit-test it.
676 * @param stdClass|cm_info $cm Activity
677 * @param int $userid ID of user
678 * @param stdClass $current Previous completion information from database
681 public function internal_get_state($cm, $userid, $current) {
689 $newstate = COMPLETION_COMPLETE
;
690 if ($cm instanceof stdClass
) {
691 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it.
692 if (!isset($cm->modname
)) {
693 $cm->modname
= $DB->get_field('modules', 'name', array('id' => $cm->module
));
695 // Some functions call this method and pass $cm as an object with ID only. Make sure course is set as well.
696 if (!isset($cm->course
)) {
697 $cm->course
= $this->course_id
;
700 // Make sure we're using a cm_info object.
701 $cminfo = cm_info
::create($cm, $userid);
702 $completionstate = $this->get_core_completion_state($cminfo, $userid);
704 if (plugin_supports('mod', $cminfo->modname
, FEATURE_COMPLETION_HAS_RULES
)) {
706 $cmcompletionclass = activity_custom_completion
::get_cm_completion_class($cminfo->modname
);
707 if ($cmcompletionclass) {
708 /** @var activity_custom_completion $cmcompletion */
709 $cmcompletion = new $cmcompletionclass($cminfo, $userid, $completionstate);
710 $response = $cmcompletion->get_overall_completion_state() != COMPLETION_INCOMPLETE
;
712 // Fallback to the get_completion_state callback.
713 $cmcompletionclass = "mod_{$cminfo->modname}\\completion\\custom_completion";
714 $function = $cminfo->modname
. '_get_completion_state';
715 if (!function_exists($function)) {
716 $this->internal_systemerror("Module {$cminfo->modname} claims to support FEATURE_COMPLETION_HAS_RULES " .
717 "but does not implement the custom completion class $cmcompletionclass which extends " .
718 "\core_completion\activity_custom_completion.");
720 debugging("*_get_completion_state() callback functions such as $function have been deprecated and should no " .
721 "longer be used. Please implement the custom completion class $cmcompletionclass which extends " .
722 "\core_completion\activity_custom_completion.", DEBUG_DEVELOPER
);
723 $response = $function($this->course
, $cm, $userid, COMPLETION_AND
, $completionstate);
727 return COMPLETION_INCOMPLETE
;
731 if ($completionstate) {
732 // We have allowed the plugins to do it's thing and run their own checks.
733 // We have now reached a state where we need to AND all the calculated results.
734 // Preference for COMPLETION_COMPLETE_PASS over COMPLETION_COMPLETE for proper indication in reports.
735 $newstate = array_reduce($completionstate, function($carry, $value) {
736 if (in_array(COMPLETION_INCOMPLETE
, [$carry, $value])) {
737 return COMPLETION_INCOMPLETE
;
738 } else if (in_array(COMPLETION_COMPLETE_FAIL
, [$carry, $value])) {
739 return COMPLETION_COMPLETE_FAIL
;
741 return in_array(COMPLETION_COMPLETE_PASS
, [$carry, $value]) ? COMPLETION_COMPLETE_PASS
: $value;
744 }, COMPLETION_COMPLETE
);
752 * Fetches the completion state for an activity completion's require grade completion requirement.
754 * @param cm_info $cm The course module information.
755 * @param int $userid The user ID.
756 * @return int The completion state.
758 public function get_grade_completion(cm_info
$cm, int $userid): int {
761 require_once($CFG->libdir
. '/gradelib.php');
762 $item = grade_item
::fetch([
763 'courseid' => $cm->course
,
765 'itemmodule' => $cm->modname
,
766 'iteminstance' => $cm->instance
,
767 'itemnumber' => $cm->completiongradeitemnumber
770 // Fetch 'grades' (will be one or none).
771 $grades = grade_grade
::fetch_users_grades($item, [$userid], false);
772 if (empty($grades)) {
773 // No grade for user.
774 return COMPLETION_INCOMPLETE
;
776 if (count($grades) > 1) {
777 $this->internal_systemerror("Unexpected result: multiple grades for
778 item '{$item->id}', user '{$userid}'");
780 return self
::internal_get_grade_state($item, reset($grades));
783 return COMPLETION_INCOMPLETE
;
787 * Marks a module as viewed.
789 * Should be called whenever a module is 'viewed' (it is up to the module how to
790 * determine that). Has no effect if viewing is not set as a completion condition.
792 * Note that this function must be called before you print the page header because
793 * it is possible that the navigation block may depend on it. If you call it after
794 * printing the header, it shows a developer debug warning.
796 * @param stdClass|cm_info $cm Activity
797 * @param int $userid User ID or 0 (default) for current user
800 public function set_module_viewed($cm, $userid=0) {
802 if ($PAGE->headerprinted
) {
803 debugging('set_module_viewed must be called before header is printed',
807 // Don't do anything if view condition is not turned on
808 if ($cm->completionview
== COMPLETION_VIEW_NOT_REQUIRED ||
!$this->is_enabled($cm)) {
812 // Get current completion state
813 $data = $this->get_data($cm, false, $userid);
815 // If we already viewed it, don't do anything unless the completion status is overridden.
816 // If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
817 if ($data->viewed
== COMPLETION_VIEWED
&& empty($data->overrideby
)) {
821 // OK, change state, save it, and update completion
822 $data->viewed
= COMPLETION_VIEWED
;
823 $this->internal_set_data($cm, $data);
824 $this->update_state($cm, COMPLETION_COMPLETE
, $userid);
828 * Determines how much completion data exists for an activity. This is used when
829 * deciding whether completion information should be 'locked' in the module
832 * @param cm_info $cm Activity
833 * @return int The number of users who have completion data stored for this
834 * activity, 0 if none
836 public function count_user_data($cm) {
839 return $DB->get_field_sql("
843 {course_modules_completion}
845 coursemoduleid=? AND completionstate<>0", array($cm->id
));
849 * Determines how much course completion data exists for a course. This is used when
850 * deciding whether completion information should be 'locked' in the completion
851 * settings form and activity completion settings.
853 * @param int $user_id Optionally only get course completion data for a single user
854 * @return int The number of users who have completion data stored for this
857 public function count_course_user_data($user_id = null) {
864 {course_completion_crit_compl}
869 $params = array($this->course_id
);
871 // Limit data to a single user if an ID is supplied
873 $sql .= ' AND userid = ?';
874 $params[] = $user_id;
877 return $DB->get_field_sql($sql, $params);
881 * Check if this course's completion criteria should be locked
885 public function is_course_locked() {
886 return (bool) $this->count_course_user_data();
890 * Deletes all course completion completion data.
892 * Intended to be used when unlocking completion criteria settings.
894 public function delete_course_completion_data() {
897 $DB->delete_records('course_completions', array('course' => $this->course_id
));
898 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id
));
900 // Difficult to find affected users, just purge all completion cache.
901 cache
::make('core', 'completion')->purge();
902 cache
::make('core', 'coursecompletion')->purge();
906 * Deletes all activity and course completion data for an entire course
907 * (the below delete_all_state function does this for a single activity).
909 * Used by course reset page.
911 public function delete_all_completion_data() {
914 // Delete from database.
915 $DB->delete_records_select('course_modules_completion',
916 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
917 array($this->course_id
));
919 // Wipe course completion data too.
920 $this->delete_course_completion_data();
924 * Deletes completion state related to an activity for all users.
926 * Intended for use only when the activity itself is deleted.
928 * @param stdClass|cm_info $cm Activity
930 public function delete_all_state($cm) {
933 // Delete from database
934 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id
));
936 // Check if there is an associated course completion criteria
937 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY
);
939 foreach ($criteria as $criterion) {
940 if ($criterion->moduleinstance
== $cm->id
) {
941 $acriteria = $criterion;
947 // Delete all criteria completions relating to this activity
948 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id
, 'criteriaid' => $acriteria->id
));
949 $DB->delete_records('course_completions', array('course' => $this->course_id
));
952 // Difficult to find affected users, just purge all completion cache.
953 cache
::make('core', 'completion')->purge();
954 cache
::make('core', 'coursecompletion')->purge();
958 * Recalculates completion state related to an activity for all users.
960 * Intended for use if completion conditions change. (This should be avoided
961 * as it may cause some things to become incomplete when they were previously
962 * complete, with the effect - for example - of hiding a later activity that
963 * was previously available.)
965 * Resetting state of manual tickbox has same result as deleting state for
968 * @param stcClass|cm_info $cm Activity
970 public function reset_all_state($cm) {
973 if ($cm->completion
== COMPLETION_TRACKING_MANUAL
) {
974 $this->delete_all_state($cm);
977 // Get current list of users with completion state
978 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id
), '', 'userid');
979 $keepusers = array();
980 foreach ($rs as $rec) {
981 $keepusers[] = $rec->userid
;
985 // Delete all existing state.
986 $this->delete_all_state($cm);
988 // Merge this with list of planned users (according to roles)
989 $trackedusers = $this->get_tracked_users();
990 foreach ($trackedusers as $trackeduser) {
991 $keepusers[] = $trackeduser->id
;
993 $keepusers = array_unique($keepusers);
995 // Recalculate state for each kept user
996 foreach ($keepusers as $keepuser) {
997 $this->update_state($cm, COMPLETION_UNKNOWN
, $keepuser);
1002 * Obtains completion data for a particular activity and user (from the
1003 * completion cache if available, or by SQL query)
1005 * @param stdClass|cm_info $cm Activity; only required field is ->id
1006 * @param bool $wholecourse If true (default false) then, when necessary to
1007 * fill the cache, retrieves information from the entire course not just for
1009 * @param int $userid User ID or 0 (default) for current user
1010 * @param array $modinfo Supply the value here - this is used for unit
1011 * testing and so that it can be called recursively from within
1012 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
1013 * Otherwise the method calls get_fast_modinfo itself.
1014 * @return object Completion data. Record from course_modules_completion plus other completion statuses such as
1015 * - Completion status for 'must-receive-grade' completion rule.
1016 * - Custom completion statuses defined by the activity module plugin.
1018 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
1020 $completioncache = cache
::make('core', 'completion');
1024 $userid = $USER->id
;
1027 // Some call completion_info::get_data and pass $cm as an object with ID only. Make sure course is set as well.
1028 if ($cm instanceof stdClass
&& !isset($cm->course
)) {
1029 $cm->course
= $this->course_id
;
1031 // Make sure we're working on a cm_info object.
1032 $cminfo = cm_info
::create($cm, $userid);
1034 // Create an anonymous function to remove the 'other_cm_completion_data_fetched' key.
1035 $returnfilteredvalue = function(array $value): stdClass
{
1036 return (object) array_filter($value, function(string $key): bool {
1037 return $key !== 'other_cm_completion_data_fetched';
1038 }, ARRAY_FILTER_USE_KEY
);
1041 // See if requested data is present in cache (use cache for current user only).
1042 $usecache = $userid == $USER->id
;
1043 $cacheddata = array();
1045 $key = $userid . '_' . $this->course
->id
;
1046 if (!isset($this->course
->cacherev
)) {
1047 $this->course
= get_course($this->course_id
);
1049 if ($cacheddata = $completioncache->get($key)) {
1050 if ($cacheddata['cacherev'] != $this->course
->cacherev
) {
1051 // Course structure has been changed since the last caching, forget the cache.
1052 $cacheddata = array();
1053 } else if (isset($cacheddata[$cminfo->id
])) {
1054 $data = (array) $cacheddata[$cminfo->id
];
1055 if (empty($data['other_cm_completion_data_fetched'])) {
1056 $data +
= $this->get_other_cm_completion_data($cminfo, $userid);
1057 $data['other_cm_completion_data_fetched'] = true;
1060 $cacheddata[$cminfo->id
] = $data;
1061 $completioncache->set($key, $cacheddata);
1064 return $returnfilteredvalue($cacheddata[$cminfo->id
]);
1069 // Default data to return when no completion data is found.
1072 'coursemoduleid' => $cminfo->id
,
1073 'userid' => $userid,
1074 'completionstate' => 0,
1076 'overrideby' => null,
1077 'timemodified' => 0,
1080 // If cached completion data is not found, fetch via SQL.
1081 // Fetch completion data for all of the activities in the course ONLY if we're caching the fetched completion data.
1082 // If we're not caching the completion data, then just fetch the completion data for the user in this course module.
1083 if ($usecache && $wholecourse) {
1084 // Get whole course data for cache.
1085 $alldatabycmc = $DB->get_records_sql("SELECT cm.id AS cmid, cmc.*
1086 FROM {course_modules} cm
1087 LEFT JOIN {course_modules_completion} cmc ON cmc.coursemoduleid = cm.id
1089 INNER JOIN {modules} m ON m.id = cm.module
1090 WHERE m.visible = 1 AND cm.course = ?", [$userid, $this->course
->id
]);
1092 $cminfos = get_fast_modinfo($cm->course
, $userid)->get_cms();
1094 // Reindex by course module id.
1095 foreach ($alldatabycmc as $data) {
1097 // Filter acitivites with no cm_info (missing plugins or other causes).
1098 if (!isset($cminfos[$data->cmid
])) {
1102 if (empty($data->coursemoduleid
)) {
1103 $cacheddata[$data->cmid
] = $defaultdata;
1104 $cacheddata[$data->cmid
]['coursemoduleid'] = $data->cmid
;
1107 $cacheddata[$data->coursemoduleid
] = (array) $data;
1111 if (!isset($cacheddata[$cminfo->id
])) {
1112 $errormessage = "Unexpected error: course-module {$cminfo->id} could not be found on course {$this->course->id}";
1113 $this->internal_systemerror($errormessage);
1116 $data = $cacheddata[$cminfo->id
];
1118 // Get single record
1119 $data = $DB->get_record('course_modules_completion', array('coursemoduleid' => $cminfo->id
, 'userid' => $userid));
1121 $data = (array)$data;
1123 // Row not present counts as 'not complete'.
1124 $data = $defaultdata;
1128 $cacheddata[$cminfo->id
] = $data;
1131 // Fill the other completion data for this user in this module instance.
1132 $data +
= $this->get_other_cm_completion_data($cminfo, $userid);
1133 $data['other_cm_completion_data_fetched'] = true;
1136 $cacheddata[$cminfo->id
] = $data;
1139 $cacheddata['cacherev'] = $this->course
->cacherev
;
1140 $completioncache->set($key, $cacheddata);
1143 return $returnfilteredvalue($cacheddata[$cminfo->id
]);
1147 * Get the latest completion state for each criteria used in the module
1149 * @param cm_info $cm The corresponding module's information
1150 * @param int $userid The id for the user we are calculating core completion state
1151 * @return array $data The individualised core completion state used in the module.
1152 * Consists of the following keys completiongrade, passgrade, viewed
1154 public function get_core_completion_state(cm_info
$cm, int $userid): array {
1157 // Include in the completion info the grade completion, if necessary.
1158 if (!is_null($cm->completiongradeitemnumber
)) {
1159 $newstate = $this->get_grade_completion($cm, $userid);
1160 $data['completiongrade'] = $newstate;
1162 if ($cm->completionpassgrade
) {
1163 // If we are asking to use pass grade completion but haven't set it properly,
1164 // then default to COMPLETION_COMPLETE_PASS.
1165 if ($newstate == COMPLETION_COMPLETE
) {
1166 $newstate = COMPLETION_COMPLETE_PASS
;
1169 // The activity is using 'passing grade' criteria therefore fail indication should be on this criteria.
1170 // The user has received a (failing) grade so 'completiongrade' should properly indicate this.
1171 if ($newstate == COMPLETION_COMPLETE_FAIL
) {
1172 $data['completiongrade'] = COMPLETION_COMPLETE
;
1175 $data['passgrade'] = $newstate;
1179 // If view is required, try and fetch from the db. In some cases, cache can be invalid.
1180 if ($cm->completionview
== COMPLETION_VIEW_REQUIRED
) {
1181 $data['viewed'] = COMPLETION_INCOMPLETE
;
1182 $record = $DB->get_record('course_modules_completion', array('coursemoduleid' => $cm->id
, 'userid' => $userid));
1184 $data['viewed'] = ($record->viewed
== COMPLETION_VIEWED ? COMPLETION_COMPLETE
: COMPLETION_INCOMPLETE
);
1192 * Adds the user's custom completion data on the given course module.
1194 * @param cm_info $cm The course module information.
1195 * @param int $userid The user ID.
1196 * @return array The additional completion data.
1198 protected function get_other_cm_completion_data(cm_info
$cm, int $userid): array {
1199 $data = $this->get_core_completion_state($cm, $userid);
1201 // Custom activity module completion data.
1203 // Cast custom data to array before checking for custom completion rules.
1204 // We call ->get_custom_data() instead of ->customdata here because there is the chance of recursive calling,
1205 // and we cannot call a getter from a getter in PHP.
1206 $customdata = (array) $cm->get_custom_data();
1207 // Return early if the plugin does not define custom completion rules.
1208 if (empty($customdata['customcompletionrules'])) {
1212 // Return early if the activity modules doe not implement the activity_custom_completion class.
1213 $cmcompletionclass = activity_custom_completion
::get_cm_completion_class($cm->modname
);
1214 if (!$cmcompletionclass) {
1218 /** @var activity_custom_completion $customcmcompletion */
1219 $customcmcompletion = new $cmcompletionclass($cm, $userid, $data);
1220 foreach ($customdata['customcompletionrules'] as $rule => $enabled) {
1222 // Skip inactive completion rules.
1225 // Get this custom completion rule's completion state.
1226 $data['customcompletion'][$rule] = $customcmcompletion->get_state($rule);
1233 * Updates completion data for a particular coursemodule and user (user is
1234 * determined from $data).
1236 * (Internal function. Not private, so we can unit-test it.)
1238 * @param stdClass|cm_info $cm Activity
1239 * @param stdClass $data Data about completion for that user
1240 * @param bool $isbulkupdate If bulk grade update is happening.
1242 public function internal_set_data($cm, $data, $isbulkupdate = false) {
1243 global $USER, $DB, $CFG;
1244 require_once($CFG->dirroot
.'/completion/criteria/completion_criteria_activity.php');
1246 $transaction = $DB->start_delegated_transaction();
1248 // Check there isn't really a row
1249 $data->id
= $DB->get_field('course_modules_completion', 'id',
1250 array('coursemoduleid'=>$data->coursemoduleid
, 'userid'=>$data->userid
));
1253 // Didn't exist before, needs creating
1254 $data->id
= $DB->insert_record('course_modules_completion', $data);
1256 // Has real (nonzero) id meaning that a database row exists, update
1257 $DB->update_record('course_modules_completion', $data);
1259 $transaction->allow_commit();
1261 $cmcontext = context_module
::instance($data->coursemoduleid
);
1263 $completioncache = cache
::make('core', 'completion');
1264 $cachekey = "{$data->userid}_{$cm->course}";
1265 if ($data->userid
== $USER->id
) {
1266 // Fetch other completion data to cache (e.g. require grade completion status, custom completion rule statues).
1267 $cminfo = cm_info
::create($cm, $data->userid
); // Make sure we're working on a cm_info object.
1268 $otherdata = $this->get_other_cm_completion_data($cminfo, $data->userid
);
1269 foreach ($otherdata as $key => $value) {
1270 $data->$key = $value;
1273 // Update module completion in user's cache.
1274 if (!($cachedata = $completioncache->get($cachekey))
1275 ||
$cachedata['cacherev'] != $this->course
->cacherev
) {
1276 $cachedata = array('cacherev' => $this->course
->cacherev
);
1278 $cachedata[$cm->id
] = (array) $data;
1279 $cachedata[$cm->id
]['other_cm_completion_data_fetched'] = true;
1280 $completioncache->set($cachekey, $cachedata);
1282 // reset modinfo for user (no need to call rebuild_course_cache())
1283 get_fast_modinfo($cm->course
, 0, true);
1285 // Remove another user's completion cache for this course.
1286 $completioncache->delete($cachekey);
1289 // For single user actions the code must reevaluate some completion state instantly, see MDL-32103.
1290 if ($isbulkupdate) {
1293 $userdata = ['userid' => $data->userid
, 'courseid' => $this->course_id
];
1294 $coursecompletionid = \core_completion\api
::mark_course_completions_activity_criteria($userdata);
1295 if ($coursecompletionid) {
1296 aggregate_completions($coursecompletionid);
1300 // Trigger an event for course module completion changed.
1301 $event = \core\event\course_module_completion_updated
::create(array(
1302 'objectid' => $data->id
,
1303 'context' => $cmcontext,
1304 'relateduserid' => $data->userid
,
1306 'relateduserid' => $data->userid
,
1307 'overrideby' => $data->overrideby
,
1308 'completionstate' => $data->completionstate
1311 $event->add_record_snapshot('course_modules_completion', $data);
1316 * Return whether or not the course has activities with completion enabled.
1318 * @return boolean true when there is at least one activity with completion enabled.
1320 public function has_activities() {
1321 $modinfo = get_fast_modinfo($this->course
);
1322 foreach ($modinfo->get_cms() as $cm) {
1323 if ($cm->completion
!= COMPLETION_TRACKING_NONE
) {
1331 * Obtains a list of activities for which completion is enabled on the
1332 * course. The list is ordered by the section order of those activities.
1334 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1335 * empty array if none
1337 public function get_activities() {
1338 $modinfo = get_fast_modinfo($this->course
);
1340 foreach ($modinfo->get_cms() as $cm) {
1341 if ($cm->completion
!= COMPLETION_TRACKING_NONE
&& !$cm->deletioninprogress
) {
1342 $result[$cm->id
] = $cm;
1349 * Checks to see if the userid supplied has a tracked role in
1352 * @param int $userid User id
1355 public function is_tracked_user($userid) {
1356 return is_enrolled(context_course
::instance($this->course
->id
), $userid, 'moodle/course:isincompletionreports', true);
1360 * Returns the number of users whose progress is tracked in this course.
1362 * Optionally supply a search's where clause, or a group id.
1364 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1365 * @param array $whereparams Where clause params
1366 * @param int $groupid Group id
1367 * @return int Number of tracked users
1369 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1372 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1373 context_course
::instance($this->course
->id
), 'moodle/course:isincompletionreports', $groupid, true);
1374 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1376 $sql .= " WHERE $where";
1379 $params = array_merge($enrolledparams, $whereparams);
1380 return $DB->count_records_sql($sql, $params);
1384 * Return array of users whose progress is tracked in this course.
1386 * Optionally supply a search's where clause, group id, sorting, paging.
1388 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1389 * @param array $whereparams Where clause params (optional)
1390 * @param int $groupid Group ID to restrict to (optional)
1391 * @param string $sort Order by clause (optional)
1392 * @param int $limitfrom Result start (optional)
1393 * @param int $limitnum Result max size (optional)
1394 * @param context $extracontext If set, includes extra user information fields
1395 * as appropriate to display for current user in this context
1396 * @return array Array of user objects with user fields (including all identity fields)
1398 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1399 $sort = '', $limitfrom = '', $limitnum = '', context
$extracontext = null) {
1403 list($enrolledsql, $params) = get_enrolled_sql(
1404 context_course
::instance($this->course
->id
),
1405 'moodle/course:isincompletionreports', $groupid, true);
1407 $userfieldsapi = \core_user\fields
::for_identity($extracontext)->with_name()->excluding('id', 'idnumber');
1408 $fieldssql = $userfieldsapi->get_sql('u', true);
1409 $sql = 'SELECT u.id, u.idnumber ' . $fieldssql->selects
;
1410 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1411 $sql .= $fieldssql->joins
;
1412 $params = array_merge($params, $fieldssql->params
);
1415 $sql .= " AND $where";
1416 $params = array_merge($params, $whereparams);
1420 $sql .= " ORDER BY $sort";
1423 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1427 * Obtains progress information across a course for all users on that course, or
1428 * for all users in a specific group. Intended for use when displaying progress.
1430 * This includes only users who, in course context, have one of the roles for
1431 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1433 * Users are included (in the first array) even if they do not have
1434 * completion progress for any course-module.
1436 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1438 * @param string $where Where clause sql (optional)
1439 * @param array $where_params Where clause params (optional)
1440 * @param int $groupid Group ID or 0 (default)/false for all groups
1441 * @param int $pagesize Number of users to actually return (optional)
1442 * @param int $start User to start at if paging (optional)
1443 * @param context $extracontext If set, includes extra user information fields
1444 * as appropriate to display for current user in this context
1445 * @return stdClass with ->total and ->start (same as $start) and ->users;
1446 * an array of user objects (like mdl_user id, firstname, lastname)
1447 * containing an additional ->progress array of coursemoduleid => completionstate
1449 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1450 $sort = '', $pagesize = '', $start = '', context
$extracontext = null) {
1453 // Get list of applicable users
1454 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1455 $start, $pagesize, $extracontext);
1457 // Get progress information for these users in groups of 1, 000 (if needed)
1458 // to avoid making the SQL IN too long
1461 foreach ($users as $user) {
1462 $userids[] = $user->id
;
1463 $results[$user->id
] = $user;
1464 $results[$user->id
]->progress
= array();
1467 for($i=0; $i<count($userids); $i+
=1000) {
1468 $blocksize = count($userids)-$i < 1000 ?
count($userids)-$i : 1000;
1470 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1471 array_splice($params, 0, 0, array($this->course
->id
));
1472 $rs = $DB->get_recordset_sql("
1477 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1479 cm.course=? AND cmc.userid $insql", $params);
1480 foreach ($rs as $progress) {
1481 $progress = (object)$progress;
1482 $results[$progress->userid
]->progress
[$progress->coursemoduleid
] = $progress;
1491 * Called by grade code to inform the completion system when a grade has
1492 * been changed. If the changed grade is used to determine completion for
1493 * the course-module, then the completion status will be updated.
1495 * @param stdClass|cm_info $cm Course-module for item that owns grade
1496 * @param grade_item $item Grade item
1497 * @param stdClass $grade
1498 * @param bool $deleted
1499 * @param bool $isbulkupdate If bulk grade update is happening.
1501 public function inform_grade_changed($cm, $item, $grade, $deleted, $isbulkupdate = false) {
1502 // Bail out now if completion is not enabled for course-module, it is enabled
1503 // but is set to manual, grade is not used to compute completion, or this
1504 // is a different numbered grade
1505 if (!$this->is_enabled($cm) ||
1506 $cm->completion
== COMPLETION_TRACKING_MANUAL ||
1507 is_null($cm->completiongradeitemnumber
) ||
1508 $item->itemnumber
!= $cm->completiongradeitemnumber
) {
1512 // What is the expected result based on this grade?
1514 // Grade being deleted, so only change could be to make it incomplete
1515 $possibleresult = COMPLETION_INCOMPLETE
;
1517 $possibleresult = self
::internal_get_grade_state($item, $grade);
1520 // OK, let's update state based on this
1521 $this->update_state($cm, $possibleresult, $grade->userid
, false, $isbulkupdate);
1525 * Calculates the completion state that would result from a graded item
1526 * (where grade-based completion is turned on) based on the actual grade
1529 * Internal function. Not private, so we can unit-test it.
1531 * @param grade_item $item an instance of grade_item
1532 * @param grade_grade $grade an instance of grade_grade
1533 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1535 public static function internal_get_grade_state($item, $grade) {
1536 // If no grade is supplied or the grade doesn't have an actual value, then
1537 // this is not complete.
1538 if (!$grade ||
(is_null($grade->finalgrade
) && is_null($grade->rawgrade
))) {
1539 return COMPLETION_INCOMPLETE
;
1542 // Conditions to show pass/fail:
1543 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1544 // b) Grade is visible (neither hidden nor hidden-until)
1545 if ($item->gradepass
&& $item->gradepass
> 0.000009 && !$item->hidden
) {
1546 // Use final grade if set otherwise raw grade
1547 $score = !is_null($grade->finalgrade
) ?
$grade->finalgrade
: $grade->rawgrade
;
1549 // We are displaying and tracking pass/fail
1550 if ($score >= $item->gradepass
) {
1551 return COMPLETION_COMPLETE_PASS
;
1553 return COMPLETION_COMPLETE_FAIL
;
1556 // Not displaying pass/fail, so just if there is a grade
1557 if (!is_null($grade->finalgrade
) ||
!is_null($grade->rawgrade
)) {
1558 // Grade exists, so maybe complete now
1559 return COMPLETION_COMPLETE
;
1561 // Grade does not exist, so maybe incomplete now
1562 return COMPLETION_INCOMPLETE
;
1568 * Aggregate activity completion state
1570 * @param int $type Aggregation type (COMPLETION_* constant)
1571 * @param bool $old Old state
1572 * @param bool $new New state
1575 public static function aggregate_completion_states($type, $old, $new) {
1576 if ($type == COMPLETION_AND
) {
1577 return $old && $new;
1579 return $old ||
$new;
1584 * This is to be used only for system errors (things that shouldn't happen)
1585 * and not user-level errors.
1588 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1589 * @throws moodle_exception Exception with the error string as debug info
1591 public function internal_systemerror($error) {
1593 throw new moodle_exception('err_system','completion',
1594 $CFG->wwwroot
.'/course/view.php?id='.$this->course
->id
,null,$error);
1599 * Aggregate criteria status's as per configured aggregation method.
1601 * @param int $method COMPLETION_AGGREGATION_* constant.
1602 * @param bool $data Criteria completion status.
1603 * @param bool|null $state Aggregation state.
1605 function completion_cron_aggregate($method, $data, &$state) {
1606 if ($method == COMPLETION_AGGREGATION_ALL
) {
1607 if ($data && $state !== false) {
1612 } else if ($method == COMPLETION_AGGREGATION_ANY
) {
1615 } else if (!$data && $state === null) {
1622 * Aggregate courses completions. This function is called when activity completion status is updated
1623 * for single user. Also when regular completion task runs it aggregates completions for all courses and users.
1625 * @param int $coursecompletionid Course completion ID to update (if 0 - update for all courses and users)
1626 * @param bool $mtraceprogress To output debug info
1629 function aggregate_completions(int $coursecompletionid, bool $mtraceprogress = false) {
1632 if (!$coursecompletionid && $mtraceprogress) {
1633 mtrace('Aggregating completions');
1635 // Save time started.
1636 $timestarted = time();
1638 // Grab all criteria and their associated criteria completions.
1639 $sql = "SELECT DISTINCT c.id AS courseid, cr.id AS criteriaid, cco.userid, cr.criteriatype, ccocr.timecompleted
1640 FROM {course_completion_criteria} cr
1641 INNER JOIN {course} c ON cr.course = c.id
1642 INNER JOIN {course_completions} cco ON cco.course = c.id
1643 LEFT JOIN {course_completion_crit_compl} ccocr
1644 ON ccocr.criteriaid = cr.id AND cco.userid = ccocr.userid
1645 WHERE c.enablecompletion = 1
1646 AND cco.timecompleted IS NULL
1647 AND cco.reaggregate > 0";
1649 if ($coursecompletionid) {
1650 $sql .= " AND cco.id = ?";
1651 $param = $coursecompletionid;
1653 $sql .= " AND cco.reaggregate < ? ORDER BY courseid, cco.userid";
1654 $param = $timestarted;
1656 $rs = $DB->get_recordset_sql($sql, [$param]);
1658 // Check if result is empty.
1659 if (!$rs->valid()) {
1664 $currentuser = null;
1665 $currentcourse = null;
1668 // Grab records for current user/course.
1669 foreach ($rs as $record) {
1670 // If we are still grabbing the same users completions.
1671 if ($record->userid
=== $currentuser && $record->courseid
=== $currentcourse) {
1672 $completions[$record->criteriaid
] = $record;
1679 if (!empty($completions)) {
1680 if (!$coursecompletionid && $mtraceprogress) {
1681 mtrace('Aggregating completions for user ' . $currentuser . ' in course ' . $currentcourse);
1684 // Get course info object.
1685 $info = new \
completion_info((object)['id' => $currentcourse]);
1687 // Setup aggregation.
1688 $overall = $info->get_aggregation_method();
1689 $activity = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ACTIVITY
);
1690 $prerequisite = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_COURSE
);
1691 $role = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ROLE
);
1693 $overallstatus = null;
1694 $activitystatus = null;
1695 $prerequisitestatus = null;
1698 // Get latest timecompleted.
1699 $timecompleted = null;
1701 // Check each of the criteria.
1702 foreach ($completions as $params) {
1703 $timecompleted = max($timecompleted, $params->timecompleted
);
1704 $completion = new \
completion_criteria_completion((array)$params, false);
1706 // Handle aggregation special cases.
1707 if ($params->criteriatype
== COMPLETION_CRITERIA_TYPE_ACTIVITY
) {
1708 completion_cron_aggregate($activity, $completion->is_complete(), $activitystatus);
1709 } else if ($params->criteriatype
== COMPLETION_CRITERIA_TYPE_COURSE
) {
1710 completion_cron_aggregate($prerequisite, $completion->is_complete(), $prerequisitestatus);
1711 } else if ($params->criteriatype
== COMPLETION_CRITERIA_TYPE_ROLE
) {
1712 completion_cron_aggregate($role, $completion->is_complete(), $rolestatus);
1714 completion_cron_aggregate($overall, $completion->is_complete(), $overallstatus);
1718 // Include role criteria aggregation in overall aggregation.
1719 if ($rolestatus !== null) {
1720 completion_cron_aggregate($overall, $rolestatus, $overallstatus);
1723 // Include activity criteria aggregation in overall aggregation.
1724 if ($activitystatus !== null) {
1725 completion_cron_aggregate($overall, $activitystatus, $overallstatus);
1728 // Include prerequisite criteria aggregation in overall aggregation.
1729 if ($prerequisitestatus !== null) {
1730 completion_cron_aggregate($overall, $prerequisitestatus, $overallstatus);
1733 // If aggregation status is true, mark course complete for user.
1734 if ($overallstatus) {
1735 if (!$coursecompletionid && $mtraceprogress) {
1736 mtrace('Marking complete');
1739 $ccompletion = new \
completion_completion([
1740 'course' => $params->courseid
,
1741 'userid' => $params->userid
1743 $ccompletion->mark_complete($timecompleted);
1747 // If this is the end of the recordset, break the loop.
1748 if (!$rs->valid()) {
1753 // New/next user, update user details, reset completions.
1754 $currentuser = $record->userid
;
1755 $currentcourse = $record->courseid
;
1757 $completions[$record->criteriaid
] = $record;
1760 // Mark all users as aggregated.
1761 if ($coursecompletionid) {
1762 $select = "reaggregate > 0 AND id = ?";
1763 $param = $coursecompletionid;
1765 $select = "reaggregate > 0 AND reaggregate < ?";
1766 $param = $timestarted;
1768 // MDL-33320: for instant completions we need aggregate to work in a single run.
1769 $DB->set_field('course_completions', 'reaggregate', $timestarted - 2);
1772 $DB->set_field_select('course_completions', 'reaggregate', 0, $select, [$param]);