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 print $this->display_help_icon();
328 * Returns the 'Your progress' help icon, if completion tracking is enabled.
330 * @return string HTML code for help icon, or blank if not needed
332 public function display_help_icon() {
333 global $PAGE, $OUTPUT, $USER;
335 if ($this->is_enabled() && !$PAGE->user_is_editing() && $this->is_tracked_user($USER->id
) && isloggedin() &&
337 $result .= html_writer
::tag('div', get_string('yourprogress','completion') .
338 $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
339 'class' => 'completionprogress'));
345 * Get a course completion for a user
347 * @param int $user_id User id
348 * @param int $criteriatype Specific criteria type to return
349 * @return bool|completion_criteria_completion returns false on fail
351 public function get_completion($user_id, $criteriatype) {
352 $completions = $this->get_completions($user_id, $criteriatype);
354 if (empty($completions)) {
356 } elseif (count($completions) > 1) {
357 print_error('multipleselfcompletioncriteria', 'completion');
360 return $completions[0];
364 * Get all course criteria's completion objects for a user
366 * @param int $user_id User id
367 * @param int $criteriatype Specific criteria type to return (optional)
370 public function get_completions($user_id, $criteriatype = null) {
371 $criteria = $this->get_criteria($criteriatype);
373 $completions = array();
375 foreach ($criteria as $criterion) {
377 'course' => $this->course_id
,
378 'userid' => $user_id,
379 'criteriaid' => $criterion->id
382 $completion = new completion_criteria_completion($params);
383 $completion->attach_criteria($criterion);
385 $completions[] = $completion;
392 * Get completion object for a user and a criteria
394 * @param int $user_id User id
395 * @param completion_criteria $criteria Criteria object
396 * @return completion_criteria_completion
398 public function get_user_completion($user_id, $criteria) {
400 'course' => $this->course_id
,
401 'userid' => $user_id,
402 'criteriaid' => $criteria->id
,
405 $completion = new completion_criteria_completion($params);
410 * Check if course has completion criteria set
412 * @return bool Returns true if there are criteria
414 public function has_criteria() {
415 $criteria = $this->get_criteria();
417 return (bool) count($criteria);
421 * Get course completion criteria
423 * @param int $criteriatype Specific criteria type to return (optional)
425 public function get_criteria($criteriatype = null) {
427 // Fill cache if empty
428 if (!is_array($this->criteria
)) {
432 'course' => $this->course
->id
435 // Load criteria from database
436 $records = (array)$DB->get_records('course_completion_criteria', $params);
438 // Order records so activities are in the same order as they appear on the course view page.
440 $activitiesorder = array_keys(get_fast_modinfo($this->course
)->get_cms());
441 usort($records, function ($a, $b) use ($activitiesorder) {
442 $aidx = ($a->criteriatype
== COMPLETION_CRITERIA_TYPE_ACTIVITY
) ?
443 array_search($a->moduleinstance
, $activitiesorder) : false;
444 $bidx = ($b->criteriatype
== COMPLETION_CRITERIA_TYPE_ACTIVITY
) ?
445 array_search($b->moduleinstance
, $activitiesorder) : false;
446 if ($aidx === false ||
$bidx === false ||
$aidx == $bidx) {
449 return ($aidx < $bidx) ?
-1 : 1;
453 // Build array of criteria objects
454 $this->criteria
= array();
455 foreach ($records as $record) {
456 $this->criteria
[$record->id
] = completion_criteria
::factory((array)$record);
460 // If after all criteria
461 if ($criteriatype === null) {
462 return $this->criteria
;
465 // If we are only after a specific criteria type
467 foreach ($this->criteria
as $criterion) {
469 if ($criterion->criteriatype
!= $criteriatype) {
473 $criteria[$criterion->id
] = $criterion;
480 * Get aggregation method
482 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
483 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
485 public function get_aggregation_method($criteriatype = null) {
487 'course' => $this->course_id
,
488 'criteriatype' => $criteriatype
491 $aggregation = new completion_aggregation($params);
493 if (!$aggregation->id
) {
494 $aggregation->method
= COMPLETION_AGGREGATION_ALL
;
497 return $aggregation->method
;
501 * @deprecated since Moodle 2.8 MDL-46290.
503 public function get_incomplete_criteria() {
504 throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
508 * Clear old course completion criteria
510 public function clear_criteria() {
513 // Remove completion criteria records for the course itself, and any records that refer to the course.
514 $select = 'course = :course OR (criteriatype = :type AND courseinstance = :courseinstance)';
516 'course' => $this->course_id
,
517 'type' => COMPLETION_CRITERIA_TYPE_COURSE
,
518 'courseinstance' => $this->course_id
,
521 $DB->delete_records_select('course_completion_criteria', $select, $params);
522 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id
));
524 $this->delete_course_completion_data();
528 * Has the supplied user completed this course
530 * @param int $user_id User's id
533 public function is_course_complete($user_id) {
535 'userid' => $user_id,
536 'course' => $this->course_id
539 $ccompletion = new completion_completion($params);
540 return $ccompletion->is_complete();
544 * Check whether the supplied user can override the activity completion statuses within the current course.
546 * @param stdClass $user The user object.
547 * @return bool True if the user can override, false otherwise.
549 public function user_can_override_completion($user) {
550 return has_capability('moodle/course:overridecompletion', context_course
::instance($this->course_id
), $user);
554 * Updates (if necessary) the completion state of activity $cm for the given
557 * For manual completion, this function is called when completion is toggled
558 * with $possibleresult set to the target state.
560 * For automatic completion, this function should be called every time a module
561 * does something which might influence a user's completion state. For example,
562 * if a forum provides options for marking itself 'completed' once a user makes
563 * N posts, this function should be called every time a user makes a new post.
564 * [After the post has been saved to the database]. When calling, you do not
565 * need to pass in the new completion state. Instead this function carries out completion
566 * calculation by checking grades and viewed state itself, and calling the involved module
567 * via mod_{modulename}\\completion\\custom_completion::get_overall_completion_state() to
568 * check module-specific conditions.
570 * @param stdClass|cm_info $cm Course-module
571 * @param int $possibleresult Expected completion result. If the event that
572 * has just occurred (e.g. add post) can only result in making the activity
573 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
574 * has just occurred (e.g. delete post) can only result in making the activity
575 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
576 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
577 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
578 * processing early if the user's completion state already matches the expected
579 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
580 * must be used; these directly set the specified state.
581 * @param int $userid User ID to be updated. Default 0 = current user
582 * @param bool $override Whether manually overriding the existing completion state.
584 * @throws moodle_exception if trying to override without permission.
586 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN
, $userid=0, $override = false) {
589 // Do nothing if completion is not enabled for that activity
590 if (!$this->is_enabled($cm)) {
594 // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
596 if (!$this->user_can_override_completion($USER)) {
597 throw new required_capability_exception(context_course
::instance($this->course_id
),
598 'moodle/course:overridecompletion', 'nopermission', '');
602 // Default to current user if one is not provided.
607 // Delete the cm's cached completion data for this user if automatic completion is enabled.
608 // This ensures any changes to the status of individual completion conditions in the activity will be fetched.
609 if ($cm->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
610 $completioncache = cache
::make('core', 'completion');
611 $completionkey = $userid . '_' . $this->course
->id
;
612 $completiondata = $completioncache->get($completionkey);
614 if ($completiondata !== false) {
615 unset($completiondata[$cm->id
]);
616 $completioncache->set($completionkey, $completiondata);
620 // Get current value of completion state and do nothing if it's same as
621 // the possible result of this change. If the change is to COMPLETE and the
622 // current value is one of the COMPLETE_xx subtypes, ignore that as well
623 $current = $this->get_data($cm, false, $userid);
624 if ($possibleresult == $current->completionstate ||
625 ($possibleresult == COMPLETION_COMPLETE
&&
626 ($current->completionstate
== COMPLETION_COMPLETE_PASS ||
627 $current->completionstate
== COMPLETION_COMPLETE_FAIL
))) {
631 // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
632 // unless processing another override.
633 // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
634 // overridden to INCOMPLETE to still be processed by normal completion triggers.
635 if ($cm->completion
== COMPLETION_TRACKING_AUTOMATIC
&& !is_null($current->overrideby
)
636 && $current->completionstate
== COMPLETION_COMPLETE
&& !$override) {
640 // For manual tracking, or if overriding the completion state, we set the state directly.
641 if ($cm->completion
== COMPLETION_TRACKING_MANUAL ||
$override) {
642 switch($possibleresult) {
643 case COMPLETION_COMPLETE
:
644 case COMPLETION_INCOMPLETE
:
645 $newstate = $possibleresult;
648 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
652 $newstate = $this->internal_get_state($cm, $userid, $current);
655 // If the overall completion state has changed, update it in the cache.
656 if ($newstate != $current->completionstate
) {
657 $current->completionstate
= $newstate;
658 $current->timemodified
= time();
659 $current->overrideby
= $override ?
$USER->id
: null;
660 $this->internal_set_data($cm, $current);
665 * Calculates the completion state for an activity and user.
667 * Internal function. Not private, so we can unit-test it.
669 * @param stdClass|cm_info $cm Activity
670 * @param int $userid ID of user
671 * @param stdClass $current Previous completion information from database
674 public function internal_get_state($cm, $userid, $current) {
683 if ($cm->completionview
== COMPLETION_VIEW_REQUIRED
&&
684 $current->viewed
== COMPLETION_NOT_VIEWED
) {
686 return COMPLETION_INCOMPLETE
;
689 if ($cm instanceof stdClass
) {
690 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it.
691 if (!isset($cm->modname
)) {
692 $cm->modname
= $DB->get_field('modules', 'name', array('id' => $cm->module
));
694 // Some functions call this method and pass $cm as an object with ID only. Make sure course is set as well.
695 if (!isset($cm->course
)) {
696 $cm->course
= $this->course_id
;
699 // Make sure we're using a cm_info object.
700 $cminfo = cm_info
::create($cm, $userid);
702 $newstate = COMPLETION_COMPLETE
;
705 if (!is_null($cminfo->completiongradeitemnumber
)) {
706 $newstate = $this->get_grade_completion($cminfo, $userid);
707 if ($newstate == COMPLETION_INCOMPLETE
) {
708 return COMPLETION_INCOMPLETE
;
712 if (plugin_supports('mod', $cminfo->modname
, FEATURE_COMPLETION_HAS_RULES
)) {
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);
717 if ($cmcompletion->get_overall_completion_state() == COMPLETION_INCOMPLETE
) {
718 return COMPLETION_INCOMPLETE
;
721 // Fallback to the get_completion_state callback.
722 $cmcompletionclass = "mod_{$cminfo->modname}\\completion\\custom_completion";
723 $function = $cminfo->modname
. '_get_completion_state';
724 if (!function_exists($function)) {
725 $this->internal_systemerror("Module {$cminfo->modname} claims to support FEATURE_COMPLETION_HAS_RULES " .
726 "but does not implement the custom completion class $cmcompletionclass which extends " .
727 "\core_completion\activity_custom_completion.");
729 debugging("*_get_completion_state() callback functions such as $function have been deprecated and should no " .
730 "longer be used. Please implement the custom completion class $cmcompletionclass which extends " .
731 "\core_completion\activity_custom_completion.", DEBUG_DEVELOPER
);
732 if (!$function($this->course
, $cminfo, $userid, COMPLETION_AND
)) {
733 return COMPLETION_INCOMPLETE
;
743 * Fetches the completion state for an activity completion's require grade completion requirement.
745 * @param cm_info $cm The course module information.
746 * @param int $userid The user ID.
747 * @return int The completion state.
749 public function get_grade_completion(cm_info
$cm, int $userid): int {
752 require_once($CFG->libdir
. '/gradelib.php');
753 $item = grade_item
::fetch([
754 'courseid' => $cm->course
,
756 'itemmodule' => $cm->modname
,
757 'iteminstance' => $cm->instance
,
758 'itemnumber' => $cm->completiongradeitemnumber
761 // Fetch 'grades' (will be one or none).
762 $grades = grade_grade
::fetch_users_grades($item, [$userid], false);
763 if (empty($grades)) {
764 // No grade for user.
765 return COMPLETION_INCOMPLETE
;
767 if (count($grades) > 1) {
768 $this->internal_systemerror("Unexpected result: multiple grades for
769 item '{$item->id}', user '{$userid}'");
771 return self
::internal_get_grade_state($item, reset($grades));
773 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
774 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
777 return COMPLETION_INCOMPLETE
;
781 * Marks a module as viewed.
783 * Should be called whenever a module is 'viewed' (it is up to the module how to
784 * determine that). Has no effect if viewing is not set as a completion condition.
786 * Note that this function must be called before you print the page header because
787 * it is possible that the navigation block may depend on it. If you call it after
788 * printing the header, it shows a developer debug warning.
790 * @param stdClass|cm_info $cm Activity
791 * @param int $userid User ID or 0 (default) for current user
794 public function set_module_viewed($cm, $userid=0) {
796 if ($PAGE->headerprinted
) {
797 debugging('set_module_viewed must be called before header is printed',
801 // Don't do anything if view condition is not turned on
802 if ($cm->completionview
== COMPLETION_VIEW_NOT_REQUIRED ||
!$this->is_enabled($cm)) {
806 // Get current completion state
807 $data = $this->get_data($cm, false, $userid);
809 // If we already viewed it, don't do anything unless the completion status is overridden.
810 // If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
811 if ($data->viewed
== COMPLETION_VIEWED
&& empty($data->overrideby
)) {
815 // OK, change state, save it, and update completion
816 $data->viewed
= COMPLETION_VIEWED
;
817 $this->internal_set_data($cm, $data);
818 $this->update_state($cm, COMPLETION_COMPLETE
, $userid);
822 * Determines how much completion data exists for an activity. This is used when
823 * deciding whether completion information should be 'locked' in the module
826 * @param cm_info $cm Activity
827 * @return int The number of users who have completion data stored for this
828 * activity, 0 if none
830 public function count_user_data($cm) {
833 return $DB->get_field_sql("
837 {course_modules_completion}
839 coursemoduleid=? AND completionstate<>0", array($cm->id
));
843 * Determines how much course completion data exists for a course. This is used when
844 * deciding whether completion information should be 'locked' in the completion
845 * settings form and activity completion settings.
847 * @param int $user_id Optionally only get course completion data for a single user
848 * @return int The number of users who have completion data stored for this
851 public function count_course_user_data($user_id = null) {
858 {course_completion_crit_compl}
863 $params = array($this->course_id
);
865 // Limit data to a single user if an ID is supplied
867 $sql .= ' AND userid = ?';
868 $params[] = $user_id;
871 return $DB->get_field_sql($sql, $params);
875 * Check if this course's completion criteria should be locked
879 public function is_course_locked() {
880 return (bool) $this->count_course_user_data();
884 * Deletes all course completion completion data.
886 * Intended to be used when unlocking completion criteria settings.
888 public function delete_course_completion_data() {
891 $DB->delete_records('course_completions', array('course' => $this->course_id
));
892 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id
));
894 // Difficult to find affected users, just purge all completion cache.
895 cache
::make('core', 'completion')->purge();
896 cache
::make('core', 'coursecompletion')->purge();
900 * Deletes all activity and course completion data for an entire course
901 * (the below delete_all_state function does this for a single activity).
903 * Used by course reset page.
905 public function delete_all_completion_data() {
908 // Delete from database.
909 $DB->delete_records_select('course_modules_completion',
910 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
911 array($this->course_id
));
913 // Wipe course completion data too.
914 $this->delete_course_completion_data();
918 * Deletes completion state related to an activity for all users.
920 * Intended for use only when the activity itself is deleted.
922 * @param stdClass|cm_info $cm Activity
924 public function delete_all_state($cm) {
927 // Delete from database
928 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id
));
930 // Check if there is an associated course completion criteria
931 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY
);
933 foreach ($criteria as $criterion) {
934 if ($criterion->moduleinstance
== $cm->id
) {
935 $acriteria = $criterion;
941 // Delete all criteria completions relating to this activity
942 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id
, 'criteriaid' => $acriteria->id
));
943 $DB->delete_records('course_completions', array('course' => $this->course_id
));
946 // Difficult to find affected users, just purge all completion cache.
947 cache
::make('core', 'completion')->purge();
948 cache
::make('core', 'coursecompletion')->purge();
952 * Recalculates completion state related to an activity for all users.
954 * Intended for use if completion conditions change. (This should be avoided
955 * as it may cause some things to become incomplete when they were previously
956 * complete, with the effect - for example - of hiding a later activity that
957 * was previously available.)
959 * Resetting state of manual tickbox has same result as deleting state for
962 * @param stcClass|cm_info $cm Activity
964 public function reset_all_state($cm) {
967 if ($cm->completion
== COMPLETION_TRACKING_MANUAL
) {
968 $this->delete_all_state($cm);
971 // Get current list of users with completion state
972 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id
), '', 'userid');
973 $keepusers = array();
974 foreach ($rs as $rec) {
975 $keepusers[] = $rec->userid
;
979 // Delete all existing state.
980 $this->delete_all_state($cm);
982 // Merge this with list of planned users (according to roles)
983 $trackedusers = $this->get_tracked_users();
984 foreach ($trackedusers as $trackeduser) {
985 $keepusers[] = $trackeduser->id
;
987 $keepusers = array_unique($keepusers);
989 // Recalculate state for each kept user
990 foreach ($keepusers as $keepuser) {
991 $this->update_state($cm, COMPLETION_UNKNOWN
, $keepuser);
996 * Obtains completion data for a particular activity and user (from the
997 * completion cache if available, or by SQL query)
999 * @param stdClass|cm_info $cm Activity; only required field is ->id
1000 * @param bool $wholecourse If true (default false) then, when necessary to
1001 * fill the cache, retrieves information from the entire course not just for
1003 * @param int $userid User ID or 0 (default) for current user
1004 * @param array $modinfo Supply the value here - this is used for unit
1005 * testing and so that it can be called recursively from within
1006 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
1007 * Otherwise the method calls get_fast_modinfo itself.
1008 * @return object Completion data. Record from course_modules_completion plus other completion statuses such as
1009 * - Completion status for 'must-receive-grade' completion rule.
1010 * - Custom completion statuses defined by the activity module plugin.
1012 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
1014 $completioncache = cache
::make('core', 'completion');
1018 $userid = $USER->id
;
1021 // See if requested data is present in cache (use cache for current user only).
1022 $usecache = $userid == $USER->id
;
1023 $cacheddata = array();
1025 $key = $userid . '_' . $this->course
->id
;
1026 if (!isset($this->course
->cacherev
)) {
1027 $this->course
= get_course($this->course_id
);
1029 if ($cacheddata = $completioncache->get($key)) {
1030 if ($cacheddata['cacherev'] != $this->course
->cacherev
) {
1031 // Course structure has been changed since the last caching, forget the cache.
1032 $cacheddata = array();
1033 } else if (isset($cacheddata[$cm->id
])) {
1034 return (object)$cacheddata[$cm->id
];
1039 // Some call completion_info::get_data and pass $cm as an object with ID only. Make sure course is set as well.
1040 if ($cm instanceof stdClass
&& !isset($cm->course
)) {
1041 $cm->course
= $this->course_id
;
1043 // Make sure we're working on a cm_info object.
1044 $cminfo = cm_info
::create($cm, $userid);
1046 // Default data to return when no completion data is found.
1049 'coursemoduleid' => $cminfo->id
,
1050 'userid' => $userid,
1051 'completionstate' => 0,
1053 'overrideby' => null,
1054 'timemodified' => 0,
1057 // If cached completion data is not found, fetch via SQL.
1058 // Fetch completion data for all of the activities in the course ONLY if we're caching the fetched completion data.
1059 // If we're not caching the completion data, then just fetch the completion data for the user in this course module.
1060 if ($usecache && $wholecourse) {
1061 // Get whole course data for cache
1062 $alldatabycmc = $DB->get_records_sql("
1067 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
1069 cm.course=? AND cmc.userid=?", array($this->course
->id
, $userid));
1073 foreach ($alldatabycmc as $data) {
1074 $alldata[$data->coursemoduleid
] = (array)$data;
1077 // Get the module info and build up condition info for each one
1078 if (empty($modinfo)) {
1079 $modinfo = get_fast_modinfo($this->course
, $userid);
1081 foreach ($modinfo->cms
as $othercm) {
1082 if (isset($alldata[$othercm->id
])) {
1083 $data = $alldata[$othercm->id
];
1085 // Row not present counts as 'not complete'.
1086 $data = $defaultdata;
1087 $data['coursemoduleid'] = $othercm->id
;
1089 // Make sure we're working on a cm_info object.
1090 $othercminfo = cm_info
::create($othercm, $userid);
1091 // Add the other completion data for this user in this module instance.
1092 $data +
= $this->get_other_cm_completion_data($othercminfo, $userid);
1093 $cacheddata[$othercminfo->id
] = $data;
1096 if (!isset($cacheddata[$cminfo->id
])) {
1097 $errormessage = "Unexpected error: course-module {$cminfo->id} could not be found on course {$this->course->id}";
1098 $this->internal_systemerror($errormessage);
1102 // Get single record
1103 $data = $DB->get_record('course_modules_completion', array('coursemoduleid' => $cminfo->id
, 'userid' => $userid));
1105 $data = (array)$data;
1107 // Row not present counts as 'not complete'.
1108 $data = $defaultdata;
1110 // Fill the other completion data for this user in this module instance.
1111 $data +
= $this->get_other_cm_completion_data($cminfo, $userid);
1114 $cacheddata[$cminfo->id
] = $data;
1118 $cacheddata['cacherev'] = $this->course
->cacherev
;
1119 $completioncache->set($key, $cacheddata);
1121 return (object)$cacheddata[$cminfo->id
];
1125 * Adds the user's custom completion data on the given course module.
1127 * @param cm_info $cm The course module information.
1128 * @param int $userid The user ID.
1129 * @return array The additional completion data.
1131 protected function get_other_cm_completion_data(cm_info
$cm, int $userid): array {
1134 // Include in the completion info the grade completion, if necessary.
1135 if (!is_null($cm->completiongradeitemnumber
)) {
1136 $data['completiongrade'] = $this->get_grade_completion($cm, $userid);
1139 // Custom activity module completion data.
1141 // Cast custom data to array before checking for custom completion rules.
1142 // We call ->get_custom_data() instead of ->customdata here because there is the chance of recursive calling,
1143 // and we cannot call a getter from a getter in PHP.
1144 $customdata = (array) $cm->get_custom_data();
1145 // Return early if the plugin does not define custom completion rules.
1146 if (empty($customdata['customcompletionrules'])) {
1150 // Return early if the activity modules doe not implement the activity_custom_completion class.
1151 $cmcompletionclass = activity_custom_completion
::get_cm_completion_class($cm->modname
);
1152 if (!$cmcompletionclass) {
1156 /** @var activity_custom_completion $customcmcompletion */
1157 $customcmcompletion = new $cmcompletionclass($cm, $userid);
1158 foreach ($customdata['customcompletionrules'] as $rule => $enabled) {
1160 // Skip inactive completion rules.
1163 // Get this custom completion rule's completion state.
1164 $data['customcompletion'][$rule] = $customcmcompletion->get_state($rule);
1171 * Updates completion data for a particular coursemodule and user (user is
1172 * determined from $data).
1174 * (Internal function. Not private, so we can unit-test it.)
1176 * @param stdClass|cm_info $cm Activity
1177 * @param stdClass $data Data about completion for that user
1179 public function internal_set_data($cm, $data) {
1182 $transaction = $DB->start_delegated_transaction();
1184 // Check there isn't really a row
1185 $data->id
= $DB->get_field('course_modules_completion', 'id',
1186 array('coursemoduleid'=>$data->coursemoduleid
, 'userid'=>$data->userid
));
1189 // Didn't exist before, needs creating
1190 $data->id
= $DB->insert_record('course_modules_completion', $data);
1192 // Has real (nonzero) id meaning that a database row exists, update
1193 $DB->update_record('course_modules_completion', $data);
1195 $transaction->allow_commit();
1197 $cmcontext = context_module
::instance($data->coursemoduleid
);
1199 $completioncache = cache
::make('core', 'completion');
1200 if ($data->userid
== $USER->id
) {
1201 // Fetch other completion data to cache (e.g. require grade completion status, custom completion rule statues).
1202 $cminfo = cm_info
::create($cm, $data->userid
); // Make sure we're working on a cm_info object.
1203 $otherdata = $this->get_other_cm_completion_data($cminfo, $data->userid
);
1204 foreach ($otherdata as $key => $value) {
1205 $data->$key = $value;
1208 // Update module completion in user's cache.
1209 if (!($cachedata = $completioncache->get($data->userid
. '_' . $cm->course
))
1210 ||
$cachedata['cacherev'] != $this->course
->cacherev
) {
1211 $cachedata = array('cacherev' => $this->course
->cacherev
);
1213 $cachedata[$cm->id
] = $data;
1214 $completioncache->set($data->userid
. '_' . $cm->course
, $cachedata);
1216 // reset modinfo for user (no need to call rebuild_course_cache())
1217 get_fast_modinfo($cm->course
, 0, true);
1219 // Remove another user's completion cache for this course.
1220 $completioncache->delete($data->userid
. '_' . $cm->course
);
1223 // Trigger an event for course module completion changed.
1224 $event = \core\event\course_module_completion_updated
::create(array(
1225 'objectid' => $data->id
,
1226 'context' => $cmcontext,
1227 'relateduserid' => $data->userid
,
1229 'relateduserid' => $data->userid
,
1230 'overrideby' => $data->overrideby
,
1231 'completionstate' => $data->completionstate
1234 $event->add_record_snapshot('course_modules_completion', $data);
1239 * Return whether or not the course has activities with completion enabled.
1241 * @return boolean true when there is at least one activity with completion enabled.
1243 public function has_activities() {
1244 $modinfo = get_fast_modinfo($this->course
);
1245 foreach ($modinfo->get_cms() as $cm) {
1246 if ($cm->completion
!= COMPLETION_TRACKING_NONE
) {
1254 * Obtains a list of activities for which completion is enabled on the
1255 * course. The list is ordered by the section order of those activities.
1257 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1258 * empty array if none
1260 public function get_activities() {
1261 $modinfo = get_fast_modinfo($this->course
);
1263 foreach ($modinfo->get_cms() as $cm) {
1264 if ($cm->completion
!= COMPLETION_TRACKING_NONE
&& !$cm->deletioninprogress
) {
1265 $result[$cm->id
] = $cm;
1272 * Checks to see if the userid supplied has a tracked role in
1275 * @param int $userid User id
1278 public function is_tracked_user($userid) {
1279 return is_enrolled(context_course
::instance($this->course
->id
), $userid, 'moodle/course:isincompletionreports', true);
1283 * Returns the number of users whose progress is tracked in this course.
1285 * Optionally supply a search's where clause, or a group id.
1287 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1288 * @param array $whereparams Where clause params
1289 * @param int $groupid Group id
1290 * @return int Number of tracked users
1292 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1295 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1296 context_course
::instance($this->course
->id
), 'moodle/course:isincompletionreports', $groupid, true);
1297 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1299 $sql .= " WHERE $where";
1302 $params = array_merge($enrolledparams, $whereparams);
1303 return $DB->count_records_sql($sql, $params);
1307 * Return array of users whose progress is tracked in this course.
1309 * Optionally supply a search's where clause, group id, sorting, paging.
1311 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1312 * @param array $whereparams Where clause params (optional)
1313 * @param int $groupid Group ID to restrict to (optional)
1314 * @param string $sort Order by clause (optional)
1315 * @param int $limitfrom Result start (optional)
1316 * @param int $limitnum Result max size (optional)
1317 * @param context $extracontext If set, includes extra user information fields
1318 * as appropriate to display for current user in this context
1319 * @return array Array of user objects with standard user fields
1321 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1322 $sort = '', $limitfrom = '', $limitnum = '', context
$extracontext = null) {
1326 list($enrolledsql, $params) = get_enrolled_sql(
1327 context_course
::instance($this->course
->id
),
1328 'moodle/course:isincompletionreports', $groupid, true);
1330 // TODO Does not support custom user profile fields (MDL-70456).
1331 $userfieldsapi = \core_user\fields
::for_identity($extracontext, false)->with_name();
1332 $allusernames = $userfieldsapi->get_sql('u')->selects
;
1333 $sql = 'SELECT u.id, u.idnumber ' . $allusernames;
1334 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1337 $sql .= " AND $where";
1338 $params = array_merge($params, $whereparams);
1342 $sql .= " ORDER BY $sort";
1345 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1349 * Obtains progress information across a course for all users on that course, or
1350 * for all users in a specific group. Intended for use when displaying progress.
1352 * This includes only users who, in course context, have one of the roles for
1353 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1355 * Users are included (in the first array) even if they do not have
1356 * completion progress for any course-module.
1358 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1360 * @param string $where Where clause sql (optional)
1361 * @param array $where_params Where clause params (optional)
1362 * @param int $groupid Group ID or 0 (default)/false for all groups
1363 * @param int $pagesize Number of users to actually return (optional)
1364 * @param int $start User to start at if paging (optional)
1365 * @param context $extracontext If set, includes extra user information fields
1366 * as appropriate to display for current user in this context
1367 * @return stdClass with ->total and ->start (same as $start) and ->users;
1368 * an array of user objects (like mdl_user id, firstname, lastname)
1369 * containing an additional ->progress array of coursemoduleid => completionstate
1371 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1372 $sort = '', $pagesize = '', $start = '', context
$extracontext = null) {
1375 // Get list of applicable users
1376 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1377 $start, $pagesize, $extracontext);
1379 // Get progress information for these users in groups of 1, 000 (if needed)
1380 // to avoid making the SQL IN too long
1383 foreach ($users as $user) {
1384 $userids[] = $user->id
;
1385 $results[$user->id
] = $user;
1386 $results[$user->id
]->progress
= array();
1389 for($i=0; $i<count($userids); $i+
=1000) {
1390 $blocksize = count($userids)-$i < 1000 ?
count($userids)-$i : 1000;
1392 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1393 array_splice($params, 0, 0, array($this->course
->id
));
1394 $rs = $DB->get_recordset_sql("
1399 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1401 cm.course=? AND cmc.userid $insql", $params);
1402 foreach ($rs as $progress) {
1403 $progress = (object)$progress;
1404 $results[$progress->userid
]->progress
[$progress->coursemoduleid
] = $progress;
1413 * Called by grade code to inform the completion system when a grade has
1414 * been changed. If the changed grade is used to determine completion for
1415 * the course-module, then the completion status will be updated.
1417 * @param stdClass|cm_info $cm Course-module for item that owns grade
1418 * @param grade_item $item Grade item
1419 * @param stdClass $grade
1420 * @param bool $deleted
1422 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1423 // Bail out now if completion is not enabled for course-module, it is enabled
1424 // but is set to manual, grade is not used to compute completion, or this
1425 // is a different numbered grade
1426 if (!$this->is_enabled($cm) ||
1427 $cm->completion
== COMPLETION_TRACKING_MANUAL ||
1428 is_null($cm->completiongradeitemnumber
) ||
1429 $item->itemnumber
!= $cm->completiongradeitemnumber
) {
1433 // What is the expected result based on this grade?
1435 // Grade being deleted, so only change could be to make it incomplete
1436 $possibleresult = COMPLETION_INCOMPLETE
;
1438 $possibleresult = self
::internal_get_grade_state($item, $grade);
1441 // OK, let's update state based on this
1442 $this->update_state($cm, $possibleresult, $grade->userid
);
1446 * Calculates the completion state that would result from a graded item
1447 * (where grade-based completion is turned on) based on the actual grade
1450 * Internal function. Not private, so we can unit-test it.
1452 * @param grade_item $item an instance of grade_item
1453 * @param grade_grade $grade an instance of grade_grade
1454 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1456 public static function internal_get_grade_state($item, $grade) {
1457 // If no grade is supplied or the grade doesn't have an actual value, then
1458 // this is not complete.
1459 if (!$grade ||
(is_null($grade->finalgrade
) && is_null($grade->rawgrade
))) {
1460 return COMPLETION_INCOMPLETE
;
1463 // Conditions to show pass/fail:
1464 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1465 // b) Grade is visible (neither hidden nor hidden-until)
1466 if ($item->gradepass
&& $item->gradepass
> 0.000009 && !$item->hidden
) {
1467 // Use final grade if set otherwise raw grade
1468 $score = !is_null($grade->finalgrade
) ?
$grade->finalgrade
: $grade->rawgrade
;
1470 // We are displaying and tracking pass/fail
1471 if ($score >= $item->gradepass
) {
1472 return COMPLETION_COMPLETE_PASS
;
1474 return COMPLETION_COMPLETE_FAIL
;
1477 // Not displaying pass/fail, so just if there is a grade
1478 if (!is_null($grade->finalgrade
) ||
!is_null($grade->rawgrade
)) {
1479 // Grade exists, so maybe complete now
1480 return COMPLETION_COMPLETE
;
1482 // Grade does not exist, so maybe incomplete now
1483 return COMPLETION_INCOMPLETE
;
1489 * Aggregate activity completion state
1491 * @param int $type Aggregation type (COMPLETION_* constant)
1492 * @param bool $old Old state
1493 * @param bool $new New state
1496 public static function aggregate_completion_states($type, $old, $new) {
1497 if ($type == COMPLETION_AND
) {
1498 return $old && $new;
1500 return $old ||
$new;
1505 * This is to be used only for system errors (things that shouldn't happen)
1506 * and not user-level errors.
1509 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1510 * @throws moodle_exception Exception with the error string as debug info
1512 public function internal_systemerror($error) {
1514 throw new moodle_exception('err_system','completion',
1515 $CFG->wwwroot
.'/course/view.php?id='.$this->course
->id
,null,$error);
1520 * Aggregate criteria status's as per configured aggregation method.
1522 * @param int $method COMPLETION_AGGREGATION_* constant.
1523 * @param bool $data Criteria completion status.
1524 * @param bool|null $state Aggregation state.
1526 function completion_cron_aggregate($method, $data, &$state) {
1527 if ($method == COMPLETION_AGGREGATION_ALL
) {
1528 if ($data && $state !== false) {
1533 } else if ($method == COMPLETION_AGGREGATION_ANY
) {
1536 } else if (!$data && $state === null) {