MDL-61502 questions: add filter tests to gapselect question type.
[moodle.git] / lib / completionlib.php
blobc8bf8177e863bc27574666c4701142a3b8d9ca86
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Contains classes, functions and constants used during the tracking
19 * of activity completion for users.
21 * Completion top-level options (admin setting enablecompletion)
23 * @package core_completion
24 * @category completion
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**
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';
40 /**
41 * The completion system is enabled in this site/course
43 define('COMPLETION_ENABLED', 1);
44 /**
45 * The completion system is not enabled in this site/course
47 define('COMPLETION_DISABLED', 0);
49 /**
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);
55 /**
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);
60 /**
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);
66 /**
67 * The user has not completed this activity.
68 * This is a completion state value (course_modules_completion/completionstate)
70 define('COMPLETION_INCOMPLETE', 0);
71 /**
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);
77 /**
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);
82 /**
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);
88 /**
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);
93 /**
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
124 * none apply.
126 define('COMPLETION_OR', false);
128 * Completion details should be ANDed together and you should return true if
129 * none apply
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
147 * @access public
148 * @param int $userid Completion data's owner
149 * @param mixed $course Course object or Course ID (optional)
150 * @return boolean
152 function completion_can_view_data($userid, $course = null) {
153 global $USER;
155 if (!isloggedin()) {
156 return false;
159 if (!is_object($course)) {
160 $cid = $course;
161 $course = new stdClass();
162 $course->id = $cid;
165 // Check if this is the site course
166 if ($course->id == SITEID) {
167 $course = null;
170 // Check if completion is enabled
171 if ($course) {
172 $cinfo = new completion_info($course);
173 if (!$cinfo->is_enabled()) {
174 return false;
176 } else {
177 if (!completion_info::is_enabled_for_site()) {
178 return false;
182 // Is own user's data?
183 if ($USER->id == $userid) {
184 return true;
187 // Check capabilities
188 $personalcontext = context_user::instance($userid);
190 if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
191 return true;
192 } elseif (has_capability('report/completion:view', $personalcontext)) {
193 return true;
196 if ($course->id) {
197 $coursecontext = context_course::instance($course->id);
198 } else {
199 $coursecontext = context_system::instance();
202 if (has_capability('report/completion:view', $coursecontext)) {
203 return true;
206 return false;
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.
216 * @package core
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 */
224 private $course;
226 /* @var int Course id */
227 public $course_id;
229 /* @var array Completion criteria {@link completion_info::get_criteria()} */
230 private $criteria;
233 * Return array of aggregation methods
234 * @return array
236 public static function get_aggregation_methods() {
237 return array(
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() {
265 global $CFG;
266 return !empty($CFG->enablecompletion);
270 * Checks whether completion is enabled in a particular course and possibly
271 * activity.
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) {
280 global $CFG, $DB;
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
298 if (!$cm) {
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;
323 $result = '';
324 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
325 $result .= html_writer::tag('div', get_string('yourprogress','completion') .
326 $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
327 'class' => 'completionprogress'));
329 return $result;
333 * Get a course completion for a user
335 * @param int $user_id User id
336 * @param int $criteriatype Specific criteria type to return
337 * @return bool|completion_criteria_completion returns false on fail
339 public function get_completion($user_id, $criteriatype) {
340 $completions = $this->get_completions($user_id, $criteriatype);
342 if (empty($completions)) {
343 return false;
344 } elseif (count($completions) > 1) {
345 print_error('multipleselfcompletioncriteria', 'completion');
348 return $completions[0];
352 * Get all course criteria's completion objects for a user
354 * @param int $user_id User id
355 * @param int $criteriatype Specific criteria type to return (optional)
356 * @return array
358 public function get_completions($user_id, $criteriatype = null) {
359 $criterion = $this->get_criteria($criteriatype);
361 $completions = array();
363 foreach ($criterion as $criteria) {
364 $params = array(
365 'course' => $this->course_id,
366 'userid' => $user_id,
367 'criteriaid' => $criteria->id
370 $completion = new completion_criteria_completion($params);
371 $completion->attach_criteria($criteria);
373 $completions[] = $completion;
376 return $completions;
380 * Get completion object for a user and a criteria
382 * @param int $user_id User id
383 * @param completion_criteria $criteria Criteria object
384 * @return completion_criteria_completion
386 public function get_user_completion($user_id, $criteria) {
387 $params = array(
388 'course' => $this->course_id,
389 'userid' => $user_id,
390 'criteriaid' => $criteria->id,
393 $completion = new completion_criteria_completion($params);
394 return $completion;
398 * Check if course has completion criteria set
400 * @return bool Returns true if there are criteria
402 public function has_criteria() {
403 $criteria = $this->get_criteria();
405 return (bool) count($criteria);
409 * Get course completion criteria
411 * @param int $criteriatype Specific criteria type to return (optional)
413 public function get_criteria($criteriatype = null) {
415 // Fill cache if empty
416 if (!is_array($this->criteria)) {
417 global $DB;
419 $params = array(
420 'course' => $this->course->id
423 // Load criteria from database
424 $records = (array)$DB->get_records('course_completion_criteria', $params);
426 // Order records so activities are in the same order as they appear on the course view page.
427 if ($records) {
428 $activitiesorder = array_keys(get_fast_modinfo($this->course)->get_cms());
429 usort($records, function ($a, $b) use ($activitiesorder) {
430 $aidx = ($a->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
431 array_search($a->moduleinstance, $activitiesorder) : false;
432 $bidx = ($b->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
433 array_search($b->moduleinstance, $activitiesorder) : false;
434 if ($aidx === false || $bidx === false || $aidx == $bidx) {
435 return 0;
437 return ($aidx < $bidx) ? -1 : 1;
441 // Build array of criteria objects
442 $this->criteria = array();
443 foreach ($records as $record) {
444 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
448 // If after all criteria
449 if ($criteriatype === null) {
450 return $this->criteria;
453 // If we are only after a specific criteria type
454 $criteria = array();
455 foreach ($this->criteria as $criterion) {
457 if ($criterion->criteriatype != $criteriatype) {
458 continue;
461 $criteria[$criterion->id] = $criterion;
464 return $criteria;
468 * Get aggregation method
470 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
471 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
473 public function get_aggregation_method($criteriatype = null) {
474 $params = array(
475 'course' => $this->course_id,
476 'criteriatype' => $criteriatype
479 $aggregation = new completion_aggregation($params);
481 if (!$aggregation->id) {
482 $aggregation->method = COMPLETION_AGGREGATION_ALL;
485 return $aggregation->method;
489 * @deprecated since Moodle 2.8 MDL-46290.
491 public function get_incomplete_criteria() {
492 throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
496 * Clear old course completion criteria
498 public function clear_criteria() {
499 global $DB;
500 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id));
501 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
503 $this->delete_course_completion_data();
507 * Has the supplied user completed this course
509 * @param int $user_id User's id
510 * @return boolean
512 public function is_course_complete($user_id) {
513 $params = array(
514 'userid' => $user_id,
515 'course' => $this->course_id
518 $ccompletion = new completion_completion($params);
519 return $ccompletion->is_complete();
523 * Updates (if necessary) the completion state of activity $cm for the given
524 * user.
526 * For manual completion, this function is called when completion is toggled
527 * with $possibleresult set to the target state.
529 * For automatic completion, this function should be called every time a module
530 * does something which might influence a user's completion state. For example,
531 * if a forum provides options for marking itself 'completed' once a user makes
532 * N posts, this function should be called every time a user makes a new post.
533 * [After the post has been saved to the database]. When calling, you do not
534 * need to pass in the new completion state. Instead this function carries out
535 * completion calculation by checking grades and viewed state itself, and
536 * calling the involved module via modulename_get_completion_state() to check
537 * module-specific conditions.
539 * @param stdClass|cm_info $cm Course-module
540 * @param int $possibleresult Expected completion result. If the event that
541 * has just occurred (e.g. add post) can only result in making the activity
542 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
543 * has just occurred (e.g. delete post) can only result in making the activity
544 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
545 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
546 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
547 * processing early if the user's completion state already matches the expected
548 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
549 * must be used; these directly set the specified state.
550 * @param int $userid User ID to be updated. Default 0 = current user
551 * @return void
553 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
554 global $USER;
556 // Do nothing if completion is not enabled for that activity
557 if (!$this->is_enabled($cm)) {
558 return;
561 // Get current value of completion state and do nothing if it's same as
562 // the possible result of this change. If the change is to COMPLETE and the
563 // current value is one of the COMPLETE_xx subtypes, ignore that as well
564 $current = $this->get_data($cm, false, $userid);
565 if ($possibleresult == $current->completionstate ||
566 ($possibleresult == COMPLETION_COMPLETE &&
567 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
568 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
569 return;
572 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
573 // For manual tracking we set the result directly
574 switch($possibleresult) {
575 case COMPLETION_COMPLETE:
576 case COMPLETION_INCOMPLETE:
577 $newstate = $possibleresult;
578 break;
579 default:
580 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
583 } else {
584 // Automatic tracking; get new state
585 $newstate = $this->internal_get_state($cm, $userid, $current);
588 // If changed, update
589 if ($newstate != $current->completionstate) {
590 $current->completionstate = $newstate;
591 $current->timemodified = time();
592 $this->internal_set_data($cm, $current);
597 * Calculates the completion state for an activity and user.
599 * Internal function. Not private, so we can unit-test it.
601 * @param stdClass|cm_info $cm Activity
602 * @param int $userid ID of user
603 * @param stdClass $current Previous completion information from database
604 * @return mixed
606 public function internal_get_state($cm, $userid, $current) {
607 global $USER, $DB, $CFG;
609 // Get user ID
610 if (!$userid) {
611 $userid = $USER->id;
614 // Check viewed
615 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
616 $current->viewed == COMPLETION_NOT_VIEWED) {
618 return COMPLETION_INCOMPLETE;
621 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
622 if (!isset($cm->modname)) {
623 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
626 $newstate = COMPLETION_COMPLETE;
628 // Check grade
629 if (!is_null($cm->completiongradeitemnumber)) {
630 require_once($CFG->libdir.'/gradelib.php');
631 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
632 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
633 'itemnumber'=>$cm->completiongradeitemnumber));
634 if ($item) {
635 // Fetch 'grades' (will be one or none)
636 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
637 if (empty($grades)) {
638 // No grade for user
639 return COMPLETION_INCOMPLETE;
641 if (count($grades) > 1) {
642 $this->internal_systemerror("Unexpected result: multiple grades for
643 item '{$item->id}', user '{$userid}'");
645 $newstate = self::internal_get_grade_state($item, reset($grades));
646 if ($newstate == COMPLETION_INCOMPLETE) {
647 return COMPLETION_INCOMPLETE;
650 } else {
651 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
652 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
656 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
657 $function = $cm->modname.'_get_completion_state';
658 if (!function_exists($function)) {
659 $this->internal_systemerror("Module {$cm->modname} claims to support
660 FEATURE_COMPLETION_HAS_RULES but does not have required
661 {$cm->modname}_get_completion_state function");
663 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
664 return COMPLETION_INCOMPLETE;
668 return $newstate;
673 * Marks a module as viewed.
675 * Should be called whenever a module is 'viewed' (it is up to the module how to
676 * determine that). Has no effect if viewing is not set as a completion condition.
678 * Note that this function must be called before you print the page header because
679 * it is possible that the navigation block may depend on it. If you call it after
680 * printing the header, it shows a developer debug warning.
682 * @param stdClass|cm_info $cm Activity
683 * @param int $userid User ID or 0 (default) for current user
684 * @return void
686 public function set_module_viewed($cm, $userid=0) {
687 global $PAGE;
688 if ($PAGE->headerprinted) {
689 debugging('set_module_viewed must be called before header is printed',
690 DEBUG_DEVELOPER);
693 // Don't do anything if view condition is not turned on
694 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
695 return;
698 // Get current completion state
699 $data = $this->get_data($cm, false, $userid);
701 // If we already viewed it, don't do anything
702 if ($data->viewed == COMPLETION_VIEWED) {
703 return;
706 // OK, change state, save it, and update completion
707 $data->viewed = COMPLETION_VIEWED;
708 $this->internal_set_data($cm, $data);
709 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
713 * Determines how much completion data exists for an activity. This is used when
714 * deciding whether completion information should be 'locked' in the module
715 * editing form.
717 * @param cm_info $cm Activity
718 * @return int The number of users who have completion data stored for this
719 * activity, 0 if none
721 public function count_user_data($cm) {
722 global $DB;
724 return $DB->get_field_sql("
725 SELECT
726 COUNT(1)
727 FROM
728 {course_modules_completion}
729 WHERE
730 coursemoduleid=? AND completionstate<>0", array($cm->id));
734 * Determines how much course completion data exists for a course. This is used when
735 * deciding whether completion information should be 'locked' in the completion
736 * settings form and activity completion settings.
738 * @param int $user_id Optionally only get course completion data for a single user
739 * @return int The number of users who have completion data stored for this
740 * course, 0 if none
742 public function count_course_user_data($user_id = null) {
743 global $DB;
745 $sql = '
746 SELECT
747 COUNT(1)
748 FROM
749 {course_completion_crit_compl}
750 WHERE
751 course = ?
754 $params = array($this->course_id);
756 // Limit data to a single user if an ID is supplied
757 if ($user_id) {
758 $sql .= ' AND userid = ?';
759 $params[] = $user_id;
762 return $DB->get_field_sql($sql, $params);
766 * Check if this course's completion criteria should be locked
768 * @return boolean
770 public function is_course_locked() {
771 return (bool) $this->count_course_user_data();
775 * Deletes all course completion completion data.
777 * Intended to be used when unlocking completion criteria settings.
779 public function delete_course_completion_data() {
780 global $DB;
782 $DB->delete_records('course_completions', array('course' => $this->course_id));
783 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
785 // Difficult to find affected users, just purge all completion cache.
786 cache::make('core', 'completion')->purge();
787 cache::make('core', 'coursecompletion')->purge();
791 * Deletes all activity and course completion data for an entire course
792 * (the below delete_all_state function does this for a single activity).
794 * Used by course reset page.
796 public function delete_all_completion_data() {
797 global $DB;
799 // Delete from database.
800 $DB->delete_records_select('course_modules_completion',
801 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
802 array($this->course_id));
804 // Wipe course completion data too.
805 $this->delete_course_completion_data();
809 * Deletes completion state related to an activity for all users.
811 * Intended for use only when the activity itself is deleted.
813 * @param stdClass|cm_info $cm Activity
815 public function delete_all_state($cm) {
816 global $DB;
818 // Delete from database
819 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
821 // Check if there is an associated course completion criteria
822 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
823 $acriteria = false;
824 foreach ($criteria as $criterion) {
825 if ($criterion->moduleinstance == $cm->id) {
826 $acriteria = $criterion;
827 break;
831 if ($acriteria) {
832 // Delete all criteria completions relating to this activity
833 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
834 $DB->delete_records('course_completions', array('course' => $this->course_id));
837 // Difficult to find affected users, just purge all completion cache.
838 cache::make('core', 'completion')->purge();
839 cache::make('core', 'coursecompletion')->purge();
843 * Recalculates completion state related to an activity for all users.
845 * Intended for use if completion conditions change. (This should be avoided
846 * as it may cause some things to become incomplete when they were previously
847 * complete, with the effect - for example - of hiding a later activity that
848 * was previously available.)
850 * Resetting state of manual tickbox has same result as deleting state for
851 * it.
853 * @param stcClass|cm_info $cm Activity
855 public function reset_all_state($cm) {
856 global $DB;
858 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
859 $this->delete_all_state($cm);
860 return;
862 // Get current list of users with completion state
863 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
864 $keepusers = array();
865 foreach ($rs as $rec) {
866 $keepusers[] = $rec->userid;
868 $rs->close();
870 // Delete all existing state.
871 $this->delete_all_state($cm);
873 // Merge this with list of planned users (according to roles)
874 $trackedusers = $this->get_tracked_users();
875 foreach ($trackedusers as $trackeduser) {
876 $keepusers[] = $trackeduser->id;
878 $keepusers = array_unique($keepusers);
880 // Recalculate state for each kept user
881 foreach ($keepusers as $keepuser) {
882 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
887 * Obtains completion data for a particular activity and user (from the
888 * completion cache if available, or by SQL query)
890 * @param stcClass|cm_info $cm Activity; only required field is ->id
891 * @param bool $wholecourse If true (default false) then, when necessary to
892 * fill the cache, retrieves information from the entire course not just for
893 * this one activity
894 * @param int $userid User ID or 0 (default) for current user
895 * @param array $modinfo Supply the value here - this is used for unit
896 * testing and so that it can be called recursively from within
897 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
898 * Otherwise the method calls get_fast_modinfo itself.
899 * @return object Completion data (record from course_modules_completion)
901 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
902 global $USER, $CFG, $DB;
903 $completioncache = cache::make('core', 'completion');
905 // Get user ID
906 if (!$userid) {
907 $userid = $USER->id;
910 // See if requested data is present in cache (use cache for current user only).
911 $usecache = $userid == $USER->id;
912 $cacheddata = array();
913 if ($usecache) {
914 $key = $userid . '_' . $this->course->id;
915 if (!isset($this->course->cacherev)) {
916 $this->course = get_course($this->course_id);
918 if ($cacheddata = $completioncache->get($key)) {
919 if ($cacheddata['cacherev'] != $this->course->cacherev) {
920 // Course structure has been changed since the last caching, forget the cache.
921 $cacheddata = array();
922 } else if (isset($cacheddata[$cm->id])) {
923 return (object)$cacheddata[$cm->id];
928 // Not there, get via SQL
929 if ($usecache && $wholecourse) {
930 // Get whole course data for cache
931 $alldatabycmc = $DB->get_records_sql("
932 SELECT
933 cmc.*
934 FROM
935 {course_modules} cm
936 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
937 WHERE
938 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
940 // Reindex by cm id
941 $alldata = array();
942 foreach ($alldatabycmc as $data) {
943 $alldata[$data->coursemoduleid] = (array)$data;
946 // Get the module info and build up condition info for each one
947 if (empty($modinfo)) {
948 $modinfo = get_fast_modinfo($this->course, $userid);
950 foreach ($modinfo->cms as $othercm) {
951 if (isset($alldata[$othercm->id])) {
952 $data = $alldata[$othercm->id];
953 } else {
954 // Row not present counts as 'not complete'
955 $data = array();
956 $data['id'] = 0;
957 $data['coursemoduleid'] = $othercm->id;
958 $data['userid'] = $userid;
959 $data['completionstate'] = 0;
960 $data['viewed'] = 0;
961 $data['timemodified'] = 0;
963 $cacheddata[$othercm->id] = $data;
966 if (!isset($cacheddata[$cm->id])) {
967 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
970 } else {
971 // Get single record
972 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
973 if ($data) {
974 $data = (array)$data;
975 } else {
976 // Row not present counts as 'not complete'
977 $data = array();
978 $data['id'] = 0;
979 $data['coursemoduleid'] = $cm->id;
980 $data['userid'] = $userid;
981 $data['completionstate'] = 0;
982 $data['viewed'] = 0;
983 $data['timemodified'] = 0;
986 // Put in cache
987 $cacheddata[$cm->id] = $data;
990 if ($usecache) {
991 $cacheddata['cacherev'] = $this->course->cacherev;
992 $completioncache->set($key, $cacheddata);
994 return (object)$cacheddata[$cm->id];
998 * Updates completion data for a particular coursemodule and user (user is
999 * determined from $data).
1001 * (Internal function. Not private, so we can unit-test it.)
1003 * @param stdClass|cm_info $cm Activity
1004 * @param stdClass $data Data about completion for that user
1006 public function internal_set_data($cm, $data) {
1007 global $USER, $DB;
1009 $transaction = $DB->start_delegated_transaction();
1010 if (!$data->id) {
1011 // Check there isn't really a row
1012 $data->id = $DB->get_field('course_modules_completion', 'id',
1013 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1015 if (!$data->id) {
1016 // Didn't exist before, needs creating
1017 $data->id = $DB->insert_record('course_modules_completion', $data);
1018 } else {
1019 // Has real (nonzero) id meaning that a database row exists, update
1020 $DB->update_record('course_modules_completion', $data);
1022 $transaction->allow_commit();
1024 $cmcontext = context_module::instance($data->coursemoduleid, MUST_EXIST);
1025 $coursecontext = $cmcontext->get_parent_context();
1027 $completioncache = cache::make('core', 'completion');
1028 if ($data->userid == $USER->id) {
1029 // Update module completion in user's cache.
1030 if (!($cachedata = $completioncache->get($data->userid . '_' . $cm->course))
1031 || $cachedata['cacherev'] != $this->course->cacherev) {
1032 $cachedata = array('cacherev' => $this->course->cacherev);
1034 $cachedata[$cm->id] = $data;
1035 $completioncache->set($data->userid . '_' . $cm->course, $cachedata);
1037 // reset modinfo for user (no need to call rebuild_course_cache())
1038 get_fast_modinfo($cm->course, 0, true);
1039 } else {
1040 // Remove another user's completion cache for this course.
1041 $completioncache->delete($data->userid . '_' . $cm->course);
1044 // Trigger an event for course module completion changed.
1045 $event = \core\event\course_module_completion_updated::create(array(
1046 'objectid' => $data->id,
1047 'context' => $cmcontext,
1048 'relateduserid' => $data->userid,
1049 'other' => array(
1050 'relateduserid' => $data->userid
1053 $event->add_record_snapshot('course_modules_completion', $data);
1054 $event->trigger();
1058 * Return whether or not the course has activities with completion enabled.
1060 * @return boolean true when there is at least one activity with completion enabled.
1062 public function has_activities() {
1063 $modinfo = get_fast_modinfo($this->course);
1064 foreach ($modinfo->get_cms() as $cm) {
1065 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1066 return true;
1069 return false;
1073 * Obtains a list of activities for which completion is enabled on the
1074 * course. The list is ordered by the section order of those activities.
1076 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1077 * empty array if none
1079 public function get_activities() {
1080 $modinfo = get_fast_modinfo($this->course);
1081 $result = array();
1082 foreach ($modinfo->get_cms() as $cm) {
1083 if ($cm->completion != COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) {
1084 $result[$cm->id] = $cm;
1087 return $result;
1091 * Checks to see if the userid supplied has a tracked role in
1092 * this course
1094 * @param int $userid User id
1095 * @return bool
1097 public function is_tracked_user($userid) {
1098 return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1102 * Returns the number of users whose progress is tracked in this course.
1104 * Optionally supply a search's where clause, or a group id.
1106 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1107 * @param array $whereparams Where clause params
1108 * @param int $groupid Group id
1109 * @return int Number of tracked users
1111 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1112 global $DB;
1114 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1115 context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1116 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1117 if ($where) {
1118 $sql .= " WHERE $where";
1121 $params = array_merge($enrolledparams, $whereparams);
1122 return $DB->count_records_sql($sql, $params);
1126 * Return array of users whose progress is tracked in this course.
1128 * Optionally supply a search's where clause, group id, sorting, paging.
1130 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1131 * @param array $whereparams Where clause params (optional)
1132 * @param int $groupid Group ID to restrict to (optional)
1133 * @param string $sort Order by clause (optional)
1134 * @param int $limitfrom Result start (optional)
1135 * @param int $limitnum Result max size (optional)
1136 * @param context $extracontext If set, includes extra user information fields
1137 * as appropriate to display for current user in this context
1138 * @return array Array of user objects with standard user fields
1140 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1141 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1143 global $DB;
1145 list($enrolledsql, $params) = get_enrolled_sql(
1146 context_course::instance($this->course->id),
1147 'moodle/course:isincompletionreports', $groupid, true);
1149 $allusernames = get_all_user_name_fields(true, 'u');
1150 $sql = 'SELECT u.id, u.idnumber, ' . $allusernames;
1151 if ($extracontext) {
1152 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1154 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1156 if ($where) {
1157 $sql .= " AND $where";
1158 $params = array_merge($params, $whereparams);
1161 if ($sort) {
1162 $sql .= " ORDER BY $sort";
1165 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1169 * Obtains progress information across a course for all users on that course, or
1170 * for all users in a specific group. Intended for use when displaying progress.
1172 * This includes only users who, in course context, have one of the roles for
1173 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1175 * Users are included (in the first array) even if they do not have
1176 * completion progress for any course-module.
1178 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1179 * last name
1180 * @param string $where Where clause sql (optional)
1181 * @param array $where_params Where clause params (optional)
1182 * @param int $groupid Group ID or 0 (default)/false for all groups
1183 * @param int $pagesize Number of users to actually return (optional)
1184 * @param int $start User to start at if paging (optional)
1185 * @param context $extracontext If set, includes extra user information fields
1186 * as appropriate to display for current user in this context
1187 * @return stdClass with ->total and ->start (same as $start) and ->users;
1188 * an array of user objects (like mdl_user id, firstname, lastname)
1189 * containing an additional ->progress array of coursemoduleid => completionstate
1191 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1192 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1193 global $CFG, $DB;
1195 // Get list of applicable users
1196 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1197 $start, $pagesize, $extracontext);
1199 // Get progress information for these users in groups of 1, 000 (if needed)
1200 // to avoid making the SQL IN too long
1201 $results = array();
1202 $userids = array();
1203 foreach ($users as $user) {
1204 $userids[] = $user->id;
1205 $results[$user->id] = $user;
1206 $results[$user->id]->progress = array();
1209 for($i=0; $i<count($userids); $i+=1000) {
1210 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1212 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1213 array_splice($params, 0, 0, array($this->course->id));
1214 $rs = $DB->get_recordset_sql("
1215 SELECT
1216 cmc.*
1217 FROM
1218 {course_modules} cm
1219 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1220 WHERE
1221 cm.course=? AND cmc.userid $insql", $params);
1222 foreach ($rs as $progress) {
1223 $progress = (object)$progress;
1224 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1226 $rs->close();
1229 return $results;
1233 * Called by grade code to inform the completion system when a grade has
1234 * been changed. If the changed grade is used to determine completion for
1235 * the course-module, then the completion status will be updated.
1237 * @param stdClass|cm_info $cm Course-module for item that owns grade
1238 * @param grade_item $item Grade item
1239 * @param stdClass $grade
1240 * @param bool $deleted
1242 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1243 // Bail out now if completion is not enabled for course-module, it is enabled
1244 // but is set to manual, grade is not used to compute completion, or this
1245 // is a different numbered grade
1246 if (!$this->is_enabled($cm) ||
1247 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1248 is_null($cm->completiongradeitemnumber) ||
1249 $item->itemnumber != $cm->completiongradeitemnumber) {
1250 return;
1253 // What is the expected result based on this grade?
1254 if ($deleted) {
1255 // Grade being deleted, so only change could be to make it incomplete
1256 $possibleresult = COMPLETION_INCOMPLETE;
1257 } else {
1258 $possibleresult = self::internal_get_grade_state($item, $grade);
1261 // OK, let's update state based on this
1262 $this->update_state($cm, $possibleresult, $grade->userid);
1266 * Calculates the completion state that would result from a graded item
1267 * (where grade-based completion is turned on) based on the actual grade
1268 * and settings.
1270 * Internal function. Not private, so we can unit-test it.
1272 * @param grade_item $item an instance of grade_item
1273 * @param grade_grade $grade an instance of grade_grade
1274 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1276 public static function internal_get_grade_state($item, $grade) {
1277 // If no grade is supplied or the grade doesn't have an actual value, then
1278 // this is not complete.
1279 if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1280 return COMPLETION_INCOMPLETE;
1283 // Conditions to show pass/fail:
1284 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1285 // b) Grade is visible (neither hidden nor hidden-until)
1286 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1287 // Use final grade if set otherwise raw grade
1288 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1290 // We are displaying and tracking pass/fail
1291 if ($score >= $item->gradepass) {
1292 return COMPLETION_COMPLETE_PASS;
1293 } else {
1294 return COMPLETION_COMPLETE_FAIL;
1296 } else {
1297 // Not displaying pass/fail, so just if there is a grade
1298 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1299 // Grade exists, so maybe complete now
1300 return COMPLETION_COMPLETE;
1301 } else {
1302 // Grade does not exist, so maybe incomplete now
1303 return COMPLETION_INCOMPLETE;
1309 * Aggregate activity completion state
1311 * @param int $type Aggregation type (COMPLETION_* constant)
1312 * @param bool $old Old state
1313 * @param bool $new New state
1314 * @return bool
1316 public static function aggregate_completion_states($type, $old, $new) {
1317 if ($type == COMPLETION_AND) {
1318 return $old && $new;
1319 } else {
1320 return $old || $new;
1325 * This is to be used only for system errors (things that shouldn't happen)
1326 * and not user-level errors.
1328 * @global type $CFG
1329 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1330 * @throws moodle_exception Exception with the error string as debug info
1332 public function internal_systemerror($error) {
1333 global $CFG;
1334 throw new moodle_exception('err_system','completion',
1335 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);