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 defined('MOODLE_INTERNAL') || die();
32 * Include the required completion libraries
34 require_once $CFG->dirroot.'/completion/completion_aggregation.php';
35 require_once $CFG->dirroot.'/completion/criteria/completion_criteria.php';
36 require_once $CFG->dirroot.'/completion/completion_completion.php';
37 require_once $CFG->dirroot.'/completion/completion_criteria_completion.php';
41 * The completion system is enabled in this site/course
43 define('COMPLETION_ENABLED', 1);
45 * The completion system is not enabled in this site/course
47 define('COMPLETION_DISABLED', 0);
50 * Completion tracking is disabled for this activity
51 * This is a completion tracking option per-activity (course_modules/completion)
53 define('COMPLETION_TRACKING_NONE', 0);
56 * Manual completion tracking (user ticks box) is enabled for this activity
57 * This is a completion tracking option per-activity (course_modules/completion)
59 define('COMPLETION_TRACKING_MANUAL', 1);
61 * Automatic completion tracking (system ticks box) is enabled for this activity
62 * This is a completion tracking option per-activity (course_modules/completion)
64 define('COMPLETION_TRACKING_AUTOMATIC', 2);
67 * The user has not completed this activity.
68 * This is a completion state value (course_modules_completion/completionstate)
70 define('COMPLETION_INCOMPLETE', 0);
72 * The user has completed this activity. It is not specified whether they have
73 * passed or failed it.
74 * This is a completion state value (course_modules_completion/completionstate)
76 define('COMPLETION_COMPLETE', 1);
78 * The user has completed this activity with a grade above the pass mark.
79 * This is a completion state value (course_modules_completion/completionstate)
81 define('COMPLETION_COMPLETE_PASS', 2);
83 * The user has completed this activity but their grade is less than the pass mark
84 * This is a completion state value (course_modules_completion/completionstate)
86 define('COMPLETION_COMPLETE_FAIL', 3);
89 * The effect of this change to completion status is unknown.
90 * A completion effect changes (used only in update_state)
92 define('COMPLETION_UNKNOWN', -1);
94 * The user's grade has changed, so their new state might be
95 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
96 * A completion effect changes (used only in update_state)
98 define('COMPLETION_GRADECHANGE', -2);
101 * User must view this activity.
102 * Whether view is required to create an activity (course_modules/completionview)
104 define('COMPLETION_VIEW_REQUIRED', 1);
106 * User does not need to view this activity
107 * Whether view is required to create an activity (course_modules/completionview)
109 define('COMPLETION_VIEW_NOT_REQUIRED', 0);
112 * User has viewed this activity.
113 * Completion viewed state (course_modules_completion/viewed)
115 define('COMPLETION_VIEWED', 1);
117 * User has not viewed this activity.
118 * Completion viewed state (course_modules_completion/viewed)
120 define('COMPLETION_NOT_VIEWED', 0);
123 * Completion details should be ORed together and you should return false if
126 define('COMPLETION_OR', false);
128 * Completion details should be ANDed together and you should return true if
131 define('COMPLETION_AND', true);
134 * Course completion criteria aggregation method.
136 define('COMPLETION_AGGREGATION_ALL', 1);
138 * Course completion criteria aggregation method.
140 define('COMPLETION_AGGREGATION_ANY', 2);
144 * Utility function for checking if the logged in user can view
145 * another's completion data for a particular course
148 * @param int $userid Completion data's owner
149 * @param mixed $course Course object or Course ID (optional)
152 function completion_can_view_data($userid, $course = null) {
159 if (!is_object($course)) {
161 $course = new stdClass();
165 // Check if this is the site course
166 if ($course->id == SITEID) {
170 // Check if completion is enabled
172 $cinfo = new completion_info($course);
173 if (!$cinfo->is_enabled()) {
177 if (!completion_info::is_enabled_for_site()) {
182 // Is own user's data?
183 if ($USER->id == $userid) {
187 // Check capabilities
188 $personalcontext = context_user::instance($userid);
190 if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
192 } elseif (has_capability('report/completion:view', $personalcontext)) {
197 $coursecontext = context_course::instance($course->id);
199 $coursecontext = context_system::instance();
202 if (has_capability('report/completion:view', $coursecontext)) {
211 * Class represents completion information for a course.
213 * Does not contain any data, so you can safely construct it multiple times
214 * without causing any problems.
217 * @category completion
218 * @copyright 2008 Sam Marshall
219 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
221 class completion_info {
223 /* @var stdClass Course object passed during construction */
226 /* @var int Course id */
229 /* @var array Completion criteria {@link completion_info::get_criteria()} */
233 * Return array of aggregation methods
236 public static function get_aggregation_methods() {
238 COMPLETION_AGGREGATION_ALL => get_string('all'),
239 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
244 * Constructs with course details.
246 * When instantiating a new completion info object you must provide a course
247 * object with at least id, and enablecompletion properties. Property
248 * cacherev is needed if you check completion of the current user since
249 * it is used for cache validation.
251 * @param stdClass $course Moodle course object.
253 public function __construct($course) {
254 $this->course = $course;
255 $this->course_id = $course->id;
259 * Determines whether completion is enabled across entire site.
261 * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
262 * COMPLETION_DISABLED (false) if it's complete
264 public static function is_enabled_for_site() {
266 return !empty($CFG->enablecompletion);
270 * Checks whether completion is enabled in a particular course and possibly
273 * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
274 * completion enable state.
275 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
276 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
277 * for a course-module.
279 public function is_enabled($cm = null) {
282 // First check global completion
283 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
284 return COMPLETION_DISABLED;
287 // Load data if we do not have enough
288 if (!isset($this->course->enablecompletion)) {
289 $this->course = get_course($this->course_id);
292 // Check course completion
293 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
294 return COMPLETION_DISABLED;
297 // If there was no $cm and we got this far, then it's enabled
299 return COMPLETION_ENABLED;
302 // Return course-module completion value
303 return $cm->completion;
307 * Displays the 'Your progress' help icon, if completion tracking is enabled.
308 * Just prints the result of display_help_icon().
310 * @deprecated since Moodle 2.0 - Use display_help_icon instead.
312 public function print_help_icon() {
313 print $this->display_help_icon();
317 * Returns the 'Your progress' help icon, if completion tracking is enabled.
319 * @return string HTML code for help icon, or blank if not needed
321 public function display_help_icon() {
322 global $PAGE, $OUTPUT, $USER;
324 if ($this->is_enabled() && !$PAGE->user_is_editing() && $this->is_tracked_user($USER->id) && isloggedin() &&
326 $result .= html_writer::tag('div', get_string('yourprogress','completion') .
327 $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
328 'class' => 'completionprogress'));
334 * Get a course completion for a user
336 * @param int $user_id User id
337 * @param int $criteriatype Specific criteria type to return
338 * @return bool|completion_criteria_completion returns false on fail
340 public function get_completion($user_id, $criteriatype) {
341 $completions = $this->get_completions($user_id, $criteriatype);
343 if (empty($completions)) {
345 } elseif (count($completions) > 1) {
346 print_error('multipleselfcompletioncriteria', 'completion');
349 return $completions[0];
353 * Get all course criteria's completion objects for a user
355 * @param int $user_id User id
356 * @param int $criteriatype Specific criteria type to return (optional)
359 public function get_completions($user_id, $criteriatype = null) {
360 $criteria = $this->get_criteria($criteriatype);
362 $completions = array();
364 foreach ($criteria as $criterion) {
366 'course' => $this->course_id,
367 'userid' => $user_id,
368 'criteriaid' => $criterion->id
371 $completion = new completion_criteria_completion($params);
372 $completion->attach_criteria($criterion);
374 $completions[] = $completion;
381 * Get completion object for a user and a criteria
383 * @param int $user_id User id
384 * @param completion_criteria $criteria Criteria object
385 * @return completion_criteria_completion
387 public function get_user_completion($user_id, $criteria) {
389 'course' => $this->course_id,
390 'userid' => $user_id,
391 'criteriaid' => $criteria->id,
394 $completion = new completion_criteria_completion($params);
399 * Check if course has completion criteria set
401 * @return bool Returns true if there are criteria
403 public function has_criteria() {
404 $criteria = $this->get_criteria();
406 return (bool) count($criteria);
410 * Get course completion criteria
412 * @param int $criteriatype Specific criteria type to return (optional)
414 public function get_criteria($criteriatype = null) {
416 // Fill cache if empty
417 if (!is_array($this->criteria)) {
421 'course' => $this->course->id
424 // Load criteria from database
425 $records = (array)$DB->get_records('course_completion_criteria', $params);
427 // Order records so activities are in the same order as they appear on the course view page.
429 $activitiesorder = array_keys(get_fast_modinfo($this->course)->get_cms());
430 usort($records, function ($a, $b) use ($activitiesorder) {
431 $aidx = ($a->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
432 array_search($a->moduleinstance, $activitiesorder) : false;
433 $bidx = ($b->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
434 array_search($b->moduleinstance, $activitiesorder) : false;
435 if ($aidx === false || $bidx === false || $aidx == $bidx) {
438 return ($aidx < $bidx) ? -1 : 1;
442 // Build array of criteria objects
443 $this->criteria = array();
444 foreach ($records as $record) {
445 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
449 // If after all criteria
450 if ($criteriatype === null) {
451 return $this->criteria;
454 // If we are only after a specific criteria type
456 foreach ($this->criteria as $criterion) {
458 if ($criterion->criteriatype != $criteriatype) {
462 $criteria[$criterion->id] = $criterion;
469 * Get aggregation method
471 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
472 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
474 public function get_aggregation_method($criteriatype = null) {
476 'course' => $this->course_id,
477 'criteriatype' => $criteriatype
480 $aggregation = new completion_aggregation($params);
482 if (!$aggregation->id) {
483 $aggregation->method = COMPLETION_AGGREGATION_ALL;
486 return $aggregation->method;
490 * @deprecated since Moodle 2.8 MDL-46290.
492 public function get_incomplete_criteria() {
493 throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
497 * Clear old course completion criteria
499 public function clear_criteria() {
501 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id));
502 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
504 $this->delete_course_completion_data();
508 * Has the supplied user completed this course
510 * @param int $user_id User's id
513 public function is_course_complete($user_id) {
515 'userid' => $user_id,
516 'course' => $this->course_id
519 $ccompletion = new completion_completion($params);
520 return $ccompletion->is_complete();
524 * Check whether the supplied user can override the activity completion statuses within the current course.
526 * @param stdClass $user The user object.
527 * @return bool True if the user can override, false otherwise.
529 public function user_can_override_completion($user) {
530 return has_capability('moodle/course:overridecompletion', context_course::instance($this->course_id), $user);
534 * Updates (if necessary) the completion state of activity $cm for the given
537 * For manual completion, this function is called when completion is toggled
538 * with $possibleresult set to the target state.
540 * For automatic completion, this function should be called every time a module
541 * does something which might influence a user's completion state. For example,
542 * if a forum provides options for marking itself 'completed' once a user makes
543 * N posts, this function should be called every time a user makes a new post.
544 * [After the post has been saved to the database]. When calling, you do not
545 * need to pass in the new completion state. Instead this function carries out
546 * completion calculation by checking grades and viewed state itself, and
547 * calling the involved module via modulename_get_completion_state() to check
548 * module-specific conditions.
550 * @param stdClass|cm_info $cm Course-module
551 * @param int $possibleresult Expected completion result. If the event that
552 * has just occurred (e.g. add post) can only result in making the activity
553 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
554 * has just occurred (e.g. delete post) can only result in making the activity
555 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
556 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
557 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
558 * processing early if the user's completion state already matches the expected
559 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
560 * must be used; these directly set the specified state.
561 * @param int $userid User ID to be updated. Default 0 = current user
562 * @param bool $override Whether manually overriding the existing completion state.
564 * @throws moodle_exception if trying to override without permission.
566 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0, $override = false) {
569 // Do nothing if completion is not enabled for that activity
570 if (!$this->is_enabled($cm)) {
574 // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
576 if (!$this->user_can_override_completion($USER)) {
577 throw new required_capability_exception(context_course::instance($this->course_id),
578 'moodle/course:overridecompletion', 'nopermission', '');
582 // Get current value of completion state and do nothing if it's same as
583 // the possible result of this change. If the change is to COMPLETE and the
584 // current value is one of the COMPLETE_xx subtypes, ignore that as well
585 $current = $this->get_data($cm, false, $userid);
586 if ($possibleresult == $current->completionstate ||
587 ($possibleresult == COMPLETION_COMPLETE &&
588 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
589 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
593 // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
594 // unless processing another override.
595 // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
596 // overridden to INCOMPLETE to still be processed by normal completion triggers.
597 if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC && !is_null($current->overrideby)
598 && $current->completionstate == COMPLETION_COMPLETE && !$override) {
602 // For manual tracking, or if overriding the completion state, we set the state directly.
603 if ($cm->completion == COMPLETION_TRACKING_MANUAL || $override) {
604 switch($possibleresult) {
605 case COMPLETION_COMPLETE:
606 case COMPLETION_INCOMPLETE:
607 $newstate = $possibleresult;
610 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
614 $newstate = $this->internal_get_state($cm, $userid, $current);
617 // If changed, update
618 if ($newstate != $current->completionstate) {
619 $current->completionstate = $newstate;
620 $current->timemodified = time();
621 $current->overrideby = $override ? $USER->id : null;
622 $this->internal_set_data($cm, $current);
627 * Calculates the completion state for an activity and user.
629 * Internal function. Not private, so we can unit-test it.
631 * @param stdClass|cm_info $cm Activity
632 * @param int $userid ID of user
633 * @param stdClass $current Previous completion information from database
636 public function internal_get_state($cm, $userid, $current) {
637 global $USER, $DB, $CFG;
645 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
646 $current->viewed == COMPLETION_NOT_VIEWED) {
648 return COMPLETION_INCOMPLETE;
651 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
652 if (!isset($cm->modname)) {
653 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
656 $newstate = COMPLETION_COMPLETE;
659 if (!is_null($cm->completiongradeitemnumber)) {
660 require_once($CFG->libdir.'/gradelib.php');
661 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
662 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
663 'itemnumber'=>$cm->completiongradeitemnumber));
665 // Fetch 'grades' (will be one or none)
666 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
667 if (empty($grades)) {
669 return COMPLETION_INCOMPLETE;
671 if (count($grades) > 1) {
672 $this->internal_systemerror("Unexpected result: multiple grades for
673 item '{$item->id}', user '{$userid}'");
675 $newstate = self::internal_get_grade_state($item, reset($grades));
676 if ($newstate == COMPLETION_INCOMPLETE) {
677 return COMPLETION_INCOMPLETE;
681 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
682 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
686 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
687 $function = $cm->modname.'_get_completion_state';
688 if (!function_exists($function)) {
689 $this->internal_systemerror("Module {$cm->modname} claims to support
690 FEATURE_COMPLETION_HAS_RULES but does not have required
691 {$cm->modname}_get_completion_state function");
693 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
694 return COMPLETION_INCOMPLETE;
703 * Marks a module as viewed.
705 * Should be called whenever a module is 'viewed' (it is up to the module how to
706 * determine that). Has no effect if viewing is not set as a completion condition.
708 * Note that this function must be called before you print the page header because
709 * it is possible that the navigation block may depend on it. If you call it after
710 * printing the header, it shows a developer debug warning.
712 * @param stdClass|cm_info $cm Activity
713 * @param int $userid User ID or 0 (default) for current user
716 public function set_module_viewed($cm, $userid=0) {
718 if ($PAGE->headerprinted) {
719 debugging('set_module_viewed must be called before header is printed',
723 // Don't do anything if view condition is not turned on
724 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
728 // Get current completion state
729 $data = $this->get_data($cm, false, $userid);
731 // If we already viewed it, don't do anything unless the completion status is overridden.
732 // If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
733 if ($data->viewed == COMPLETION_VIEWED && empty($data->overrideby)) {
737 // OK, change state, save it, and update completion
738 $data->viewed = COMPLETION_VIEWED;
739 $this->internal_set_data($cm, $data);
740 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
744 * Determines how much completion data exists for an activity. This is used when
745 * deciding whether completion information should be 'locked' in the module
748 * @param cm_info $cm Activity
749 * @return int The number of users who have completion data stored for this
750 * activity, 0 if none
752 public function count_user_data($cm) {
755 return $DB->get_field_sql("
759 {course_modules_completion}
761 coursemoduleid=? AND completionstate<>0", array($cm->id));
765 * Determines how much course completion data exists for a course. This is used when
766 * deciding whether completion information should be 'locked' in the completion
767 * settings form and activity completion settings.
769 * @param int $user_id Optionally only get course completion data for a single user
770 * @return int The number of users who have completion data stored for this
773 public function count_course_user_data($user_id = null) {
780 {course_completion_crit_compl}
785 $params = array($this->course_id);
787 // Limit data to a single user if an ID is supplied
789 $sql .= ' AND userid = ?';
790 $params[] = $user_id;
793 return $DB->get_field_sql($sql, $params);
797 * Check if this course's completion criteria should be locked
801 public function is_course_locked() {
802 return (bool) $this->count_course_user_data();
806 * Deletes all course completion completion data.
808 * Intended to be used when unlocking completion criteria settings.
810 public function delete_course_completion_data() {
813 $DB->delete_records('course_completions', array('course' => $this->course_id));
814 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
816 // Difficult to find affected users, just purge all completion cache.
817 cache::make('core', 'completion')->purge();
818 cache::make('core', 'coursecompletion')->purge();
822 * Deletes all activity and course completion data for an entire course
823 * (the below delete_all_state function does this for a single activity).
825 * Used by course reset page.
827 public function delete_all_completion_data() {
830 // Delete from database.
831 $DB->delete_records_select('course_modules_completion',
832 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
833 array($this->course_id));
835 // Wipe course completion data too.
836 $this->delete_course_completion_data();
840 * Deletes completion state related to an activity for all users.
842 * Intended for use only when the activity itself is deleted.
844 * @param stdClass|cm_info $cm Activity
846 public function delete_all_state($cm) {
849 // Delete from database
850 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
852 // Check if there is an associated course completion criteria
853 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
855 foreach ($criteria as $criterion) {
856 if ($criterion->moduleinstance == $cm->id) {
857 $acriteria = $criterion;
863 // Delete all criteria completions relating to this activity
864 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
865 $DB->delete_records('course_completions', array('course' => $this->course_id));
868 // Difficult to find affected users, just purge all completion cache.
869 cache::make('core', 'completion')->purge();
870 cache::make('core', 'coursecompletion')->purge();
874 * Recalculates completion state related to an activity for all users.
876 * Intended for use if completion conditions change. (This should be avoided
877 * as it may cause some things to become incomplete when they were previously
878 * complete, with the effect - for example - of hiding a later activity that
879 * was previously available.)
881 * Resetting state of manual tickbox has same result as deleting state for
884 * @param stcClass|cm_info $cm Activity
886 public function reset_all_state($cm) {
889 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
890 $this->delete_all_state($cm);
893 // Get current list of users with completion state
894 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
895 $keepusers = array();
896 foreach ($rs as $rec) {
897 $keepusers[] = $rec->userid;
901 // Delete all existing state.
902 $this->delete_all_state($cm);
904 // Merge this with list of planned users (according to roles)
905 $trackedusers = $this->get_tracked_users();
906 foreach ($trackedusers as $trackeduser) {
907 $keepusers[] = $trackeduser->id;
909 $keepusers = array_unique($keepusers);
911 // Recalculate state for each kept user
912 foreach ($keepusers as $keepuser) {
913 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
918 * Obtains completion data for a particular activity and user (from the
919 * completion cache if available, or by SQL query)
921 * @param stcClass|cm_info $cm Activity; only required field is ->id
922 * @param bool $wholecourse If true (default false) then, when necessary to
923 * fill the cache, retrieves information from the entire course not just for
925 * @param int $userid User ID or 0 (default) for current user
926 * @param array $modinfo Supply the value here - this is used for unit
927 * testing and so that it can be called recursively from within
928 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
929 * Otherwise the method calls get_fast_modinfo itself.
930 * @return object Completion data (record from course_modules_completion)
932 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
933 global $USER, $CFG, $DB;
934 $completioncache = cache::make('core', 'completion');
941 // See if requested data is present in cache (use cache for current user only).
942 $usecache = $userid == $USER->id;
943 $cacheddata = array();
945 $key = $userid . '_' . $this->course->id;
946 if (!isset($this->course->cacherev)) {
947 $this->course = get_course($this->course_id);
949 if ($cacheddata = $completioncache->get($key)) {
950 if ($cacheddata['cacherev'] != $this->course->cacherev) {
951 // Course structure has been changed since the last caching, forget the cache.
952 $cacheddata = array();
953 } else if (isset($cacheddata[$cm->id])) {
954 return (object)$cacheddata[$cm->id];
959 // Not there, get via SQL
960 if ($usecache && $wholecourse) {
961 // Get whole course data for cache
962 $alldatabycmc = $DB->get_records_sql("
967 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
969 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
973 foreach ($alldatabycmc as $data) {
974 $alldata[$data->coursemoduleid] = (array)$data;
977 // Get the module info and build up condition info for each one
978 if (empty($modinfo)) {
979 $modinfo = get_fast_modinfo($this->course, $userid);
981 foreach ($modinfo->cms as $othercm) {
982 if (isset($alldata[$othercm->id])) {
983 $data = $alldata[$othercm->id];
985 // Row not present counts as 'not complete'
988 $data['coursemoduleid'] = $othercm->id;
989 $data['userid'] = $userid;
990 $data['completionstate'] = 0;
992 $data['overrideby'] = null;
993 $data['timemodified'] = 0;
995 $cacheddata[$othercm->id] = $data;
998 if (!isset($cacheddata[$cm->id])) {
999 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
1003 // Get single record
1004 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
1006 $data = (array)$data;
1008 // Row not present counts as 'not complete'
1011 $data['coursemoduleid'] = $cm->id;
1012 $data['userid'] = $userid;
1013 $data['completionstate'] = 0;
1014 $data['viewed'] = 0;
1015 $data['overrideby'] = null;
1016 $data['timemodified'] = 0;
1020 $cacheddata[$cm->id] = $data;
1024 $cacheddata['cacherev'] = $this->course->cacherev;
1025 $completioncache->set($key, $cacheddata);
1027 return (object)$cacheddata[$cm->id];
1031 * Updates completion data for a particular coursemodule and user (user is
1032 * determined from $data).
1034 * (Internal function. Not private, so we can unit-test it.)
1036 * @param stdClass|cm_info $cm Activity
1037 * @param stdClass $data Data about completion for that user
1039 public function internal_set_data($cm, $data) {
1042 $transaction = $DB->start_delegated_transaction();
1044 // Check there isn't really a row
1045 $data->id = $DB->get_field('course_modules_completion', 'id',
1046 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1049 // Didn't exist before, needs creating
1050 $data->id = $DB->insert_record('course_modules_completion', $data);
1052 // Has real (nonzero) id meaning that a database row exists, update
1053 $DB->update_record('course_modules_completion', $data);
1055 $transaction->allow_commit();
1057 $cmcontext = context_module::instance($data->coursemoduleid, MUST_EXIST);
1058 $coursecontext = $cmcontext->get_parent_context();
1060 $completioncache = cache::make('core', 'completion');
1061 if ($data->userid == $USER->id) {
1062 // Update module completion in user's cache.
1063 if (!($cachedata = $completioncache->get($data->userid . '_' . $cm->course))
1064 || $cachedata['cacherev'] != $this->course->cacherev) {
1065 $cachedata = array('cacherev' => $this->course->cacherev);
1067 $cachedata[$cm->id] = $data;
1068 $completioncache->set($data->userid . '_' . $cm->course, $cachedata);
1070 // reset modinfo for user (no need to call rebuild_course_cache())
1071 get_fast_modinfo($cm->course, 0, true);
1073 // Remove another user's completion cache for this course.
1074 $completioncache->delete($data->userid . '_' . $cm->course);
1077 // Trigger an event for course module completion changed.
1078 $event = \core\event\course_module_completion_updated::create(array(
1079 'objectid' => $data->id,
1080 'context' => $cmcontext,
1081 'relateduserid' => $data->userid,
1083 'relateduserid' => $data->userid,
1084 'overrideby' => $data->overrideby,
1085 'completionstate' => $data->completionstate
1088 $event->add_record_snapshot('course_modules_completion', $data);
1093 * Return whether or not the course has activities with completion enabled.
1095 * @return boolean true when there is at least one activity with completion enabled.
1097 public function has_activities() {
1098 $modinfo = get_fast_modinfo($this->course);
1099 foreach ($modinfo->get_cms() as $cm) {
1100 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1108 * Obtains a list of activities for which completion is enabled on the
1109 * course. The list is ordered by the section order of those activities.
1111 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1112 * empty array if none
1114 public function get_activities() {
1115 $modinfo = get_fast_modinfo($this->course);
1117 foreach ($modinfo->get_cms() as $cm) {
1118 if ($cm->completion != COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) {
1119 $result[$cm->id] = $cm;
1126 * Checks to see if the userid supplied has a tracked role in
1129 * @param int $userid User id
1132 public function is_tracked_user($userid) {
1133 return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1137 * Returns the number of users whose progress is tracked in this course.
1139 * Optionally supply a search's where clause, or a group id.
1141 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1142 * @param array $whereparams Where clause params
1143 * @param int $groupid Group id
1144 * @return int Number of tracked users
1146 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1149 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1150 context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1151 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1153 $sql .= " WHERE $where";
1156 $params = array_merge($enrolledparams, $whereparams);
1157 return $DB->count_records_sql($sql, $params);
1161 * Return array of users whose progress is tracked in this course.
1163 * Optionally supply a search's where clause, group id, sorting, paging.
1165 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1166 * @param array $whereparams Where clause params (optional)
1167 * @param int $groupid Group ID to restrict to (optional)
1168 * @param string $sort Order by clause (optional)
1169 * @param int $limitfrom Result start (optional)
1170 * @param int $limitnum Result max size (optional)
1171 * @param context $extracontext If set, includes extra user information fields
1172 * as appropriate to display for current user in this context
1173 * @return array Array of user objects with standard user fields
1175 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1176 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1180 list($enrolledsql, $params) = get_enrolled_sql(
1181 context_course::instance($this->course->id),
1182 'moodle/course:isincompletionreports', $groupid, true);
1184 $allusernames = get_all_user_name_fields(true, 'u');
1185 $sql = 'SELECT u.id, u.idnumber, ' . $allusernames;
1186 if ($extracontext) {
1187 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1189 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1192 $sql .= " AND $where";
1193 $params = array_merge($params, $whereparams);
1197 $sql .= " ORDER BY $sort";
1200 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1204 * Obtains progress information across a course for all users on that course, or
1205 * for all users in a specific group. Intended for use when displaying progress.
1207 * This includes only users who, in course context, have one of the roles for
1208 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1210 * Users are included (in the first array) even if they do not have
1211 * completion progress for any course-module.
1213 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1215 * @param string $where Where clause sql (optional)
1216 * @param array $where_params Where clause params (optional)
1217 * @param int $groupid Group ID or 0 (default)/false for all groups
1218 * @param int $pagesize Number of users to actually return (optional)
1219 * @param int $start User to start at if paging (optional)
1220 * @param context $extracontext If set, includes extra user information fields
1221 * as appropriate to display for current user in this context
1222 * @return stdClass with ->total and ->start (same as $start) and ->users;
1223 * an array of user objects (like mdl_user id, firstname, lastname)
1224 * containing an additional ->progress array of coursemoduleid => completionstate
1226 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1227 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1230 // Get list of applicable users
1231 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1232 $start, $pagesize, $extracontext);
1234 // Get progress information for these users in groups of 1, 000 (if needed)
1235 // to avoid making the SQL IN too long
1238 foreach ($users as $user) {
1239 $userids[] = $user->id;
1240 $results[$user->id] = $user;
1241 $results[$user->id]->progress = array();
1244 for($i=0; $i<count($userids); $i+=1000) {
1245 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1247 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1248 array_splice($params, 0, 0, array($this->course->id));
1249 $rs = $DB->get_recordset_sql("
1254 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1256 cm.course=? AND cmc.userid $insql", $params);
1257 foreach ($rs as $progress) {
1258 $progress = (object)$progress;
1259 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1268 * Called by grade code to inform the completion system when a grade has
1269 * been changed. If the changed grade is used to determine completion for
1270 * the course-module, then the completion status will be updated.
1272 * @param stdClass|cm_info $cm Course-module for item that owns grade
1273 * @param grade_item $item Grade item
1274 * @param stdClass $grade
1275 * @param bool $deleted
1277 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1278 // Bail out now if completion is not enabled for course-module, it is enabled
1279 // but is set to manual, grade is not used to compute completion, or this
1280 // is a different numbered grade
1281 if (!$this->is_enabled($cm) ||
1282 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1283 is_null($cm->completiongradeitemnumber) ||
1284 $item->itemnumber != $cm->completiongradeitemnumber) {
1288 // What is the expected result based on this grade?
1290 // Grade being deleted, so only change could be to make it incomplete
1291 $possibleresult = COMPLETION_INCOMPLETE;
1293 $possibleresult = self::internal_get_grade_state($item, $grade);
1296 // OK, let's update state based on this
1297 $this->update_state($cm, $possibleresult, $grade->userid);
1301 * Calculates the completion state that would result from a graded item
1302 * (where grade-based completion is turned on) based on the actual grade
1305 * Internal function. Not private, so we can unit-test it.
1307 * @param grade_item $item an instance of grade_item
1308 * @param grade_grade $grade an instance of grade_grade
1309 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1311 public static function internal_get_grade_state($item, $grade) {
1312 // If no grade is supplied or the grade doesn't have an actual value, then
1313 // this is not complete.
1314 if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1315 return COMPLETION_INCOMPLETE;
1318 // Conditions to show pass/fail:
1319 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1320 // b) Grade is visible (neither hidden nor hidden-until)
1321 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1322 // Use final grade if set otherwise raw grade
1323 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1325 // We are displaying and tracking pass/fail
1326 if ($score >= $item->gradepass) {
1327 return COMPLETION_COMPLETE_PASS;
1329 return COMPLETION_COMPLETE_FAIL;
1332 // Not displaying pass/fail, so just if there is a grade
1333 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1334 // Grade exists, so maybe complete now
1335 return COMPLETION_COMPLETE;
1337 // Grade does not exist, so maybe incomplete now
1338 return COMPLETION_INCOMPLETE;
1344 * Aggregate activity completion state
1346 * @param int $type Aggregation type (COMPLETION_* constant)
1347 * @param bool $old Old state
1348 * @param bool $new New state
1351 public static function aggregate_completion_states($type, $old, $new) {
1352 if ($type == COMPLETION_AND) {
1353 return $old && $new;
1355 return $old || $new;
1360 * This is to be used only for system errors (things that shouldn't happen)
1361 * and not user-level errors.
1364 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1365 * @throws moodle_exception Exception with the error string as debug info
1367 public function internal_systemerror($error) {
1369 throw new moodle_exception('err_system','completion',
1370 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1375 * Aggregate criteria status's as per configured aggregation method.
1377 * @param int $method COMPLETION_AGGREGATION_* constant.
1378 * @param bool $data Criteria completion status.
1379 * @param bool|null $state Aggregation state.
1381 function completion_cron_aggregate($method, $data, &$state) {
1382 if ($method == COMPLETION_AGGREGATION_ALL) {
1383 if ($data && $state !== false) {
1388 } else if ($method == COMPLETION_AGGREGATION_ANY) {
1391 } else if (!$data && $state === null) {