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->libdir.'/completion/completion_aggregation.php';
35 require_once $CFG->libdir.'/completion/completion_criteria.php';
36 require_once $CFG->libdir.'/completion/completion_completion.php';
37 require_once $CFG->libdir.'/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 * Cache expiry time in seconds (10 minutes)
124 * Completion cacheing
126 define('COMPLETION_CACHE_EXPIRY', 10*60);
129 * Completion details should be ORed together and you should return false if
132 define('COMPLETION_OR', false);
134 * Completion details should be ANDed together and you should return true if
137 define('COMPLETION_AND', true);
140 * Course completion criteria aggregation method.
142 define('COMPLETION_AGGREGATION_ALL', 1);
144 * Course completion criteria aggregation method.
146 define('COMPLETION_AGGREGATION_ANY', 2);
150 * Class represents completion information for a course.
152 * Does not contain any data, so you can safely construct it multiple times
153 * without causing any problems.
156 * @category completion
157 * @copyright 2008 Sam Marshall
158 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
160 class completion_info {
162 /* @var stdClass Course object passed during construction */
165 /* @var int Course id */
168 /* @var array Completion criteria {@link completion_info::get_criteria()} */
172 * Return array of aggregation methods
175 public static function get_aggregation_methods() {
177 COMPLETION_AGGREGATION_ALL => get_string('all'),
178 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
183 * Constructs with course details.
185 * When instantiating a new completion info object you must provide a course
186 * object with at least id, and enablecompletion properties.
188 * @param stdClass $course Moodle course object.
190 public function __construct($course) {
191 $this->course = $course;
192 $this->course_id = $course->id;
196 * Determines whether completion is enabled across entire site.
198 * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
199 * COMPLETION_DISABLED (false) if it's complete
201 public static function is_enabled_for_site() {
203 return !empty($CFG->enablecompletion);
207 * Checks whether completion is enabled in a particular course and possibly
210 * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
211 * completion enable state.
212 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
213 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
214 * for a course-module.
216 public function is_enabled($cm = null) {
219 // First check global completion
220 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
221 return COMPLETION_DISABLED;
224 // Load data if we do not have enough
225 if (!isset($this->course->enablecompletion)) {
226 $this->course->enablecompletion = $DB->get_field('course', 'enablecompletion', array('id' => $this->course->id));
229 // Check course completion
230 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
231 return COMPLETION_DISABLED;
234 // If there was no $cm and we got this far, then it's enabled
236 return COMPLETION_ENABLED;
239 // Return course-module completion value
240 return $cm->completion;
244 * Displays the 'Your progress' help icon, if completion tracking is enabled.
245 * Just prints the result of display_help_icon().
247 * @deprecated since Moodle 2.0 - Use display_help_icon instead.
249 public function print_help_icon() {
250 print $this->display_help_icon();
254 * Returns the 'Your progress' help icon, if completion tracking is enabled.
256 * @return string HTML code for help icon, or blank if not needed
258 public function display_help_icon() {
259 global $PAGE, $OUTPUT;
261 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
262 $result .= '<span id = "completionprogressid" class="completionprogress">'.get_string('yourprogress','completion').' ';
263 $result .= $OUTPUT->help_icon('completionicons', 'completion');
264 $result .= '</span>';
270 * Get a course completion for a user
272 * @param int $user_id User id
273 * @param int $criteriatype Specific criteria type to return
274 * @return bool|completion_criteria_completion returns false on fail
276 public function get_completion($user_id, $criteriatype) {
277 $completions = $this->get_completions($user_id, $criteriatype);
279 if (empty($completions)) {
281 } elseif (count($completions) > 1) {
282 print_error('multipleselfcompletioncriteria', 'completion');
285 return $completions[0];
289 * Get all course criteria's completion objects for a user
291 * @param int $user_id User id
292 * @param int $criteriatype Specific criteria type to return (optional)
295 public function get_completions($user_id, $criteriatype = null) {
296 $criterion = $this->get_criteria($criteriatype);
298 $completions = array();
300 foreach ($criterion as $criteria) {
302 'course' => $this->course_id,
303 'userid' => $user_id,
304 'criteriaid' => $criteria->id
307 $completion = new completion_criteria_completion($params);
308 $completion->attach_criteria($criteria);
310 $completions[] = $completion;
317 * Get completion object for a user and a criteria
319 * @param int $user_id User id
320 * @param completion_criteria $criteria Criteria object
321 * @return completion_criteria_completion
323 public function get_user_completion($user_id, $criteria) {
325 'course' => $this->course_id,
326 'userid' => $user_id,
327 'criteriaid' => $criteria->id,
330 $completion = new completion_criteria_completion($params);
335 * Check if course has completion criteria set
337 * @return bool Returns true if there are criteria
339 public function has_criteria() {
340 $criteria = $this->get_criteria();
342 return (bool) count($criteria);
346 * Get course completion criteria
348 * @param int $criteriatype Specific criteria type to return (optional)
350 public function get_criteria($criteriatype = null) {
352 // Fill cache if empty
353 if (!is_array($this->criteria)) {
357 'course' => $this->course->id
360 // Load criteria from database
361 $records = (array)$DB->get_records('course_completion_criteria', $params);
363 // Build array of criteria objects
364 $this->criteria = array();
365 foreach ($records as $record) {
366 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
370 // If after all criteria
371 if ($criteriatype === null) {
372 return $this->criteria;
375 // If we are only after a specific criteria type
377 foreach ($this->criteria as $criterion) {
379 if ($criterion->criteriatype != $criteriatype) {
383 $criteria[$criterion->id] = $criterion;
390 * Get aggregation method
392 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
393 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
395 public function get_aggregation_method($criteriatype = null) {
397 'course' => $this->course_id,
398 'criteriatype' => $criteriatype
401 $aggregation = new completion_aggregation($params);
403 if (!$aggregation->id) {
404 $aggregation->method = COMPLETION_AGGREGATION_ALL;
407 return $aggregation->method;
411 * Get incomplete course completion criteria
415 public function get_incomplete_criteria() {
416 $incomplete = array();
418 foreach ($this->get_criteria() as $criteria) {
419 if (!$criteria->is_complete()) {
420 $incomplete[] = $criteria;
428 * Clear old course completion criteria
430 public function clear_criteria() {
432 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id));
433 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
435 $this->delete_course_completion_data();
439 * Has the supplied user completed this course
441 * @param int $user_id User's id
444 public function is_course_complete($user_id) {
446 'userid' => $user_id,
447 'course' => $this->course_id
450 $ccompletion = new completion_completion($params);
451 return $ccompletion->is_complete();
455 * Updates (if necessary) the completion state of activity $cm for the given
458 * For manual completion, this function is called when completion is toggled
459 * with $possibleresult set to the target state.
461 * For automatic completion, this function should be called every time a module
462 * does something which might influence a user's completion state. For example,
463 * if a forum provides options for marking itself 'completed' once a user makes
464 * N posts, this function should be called every time a user makes a new post.
465 * [After the post has been saved to the database]. When calling, you do not
466 * need to pass in the new completion state. Instead this function carries out
467 * completion calculation by checking grades and viewed state itself, and
468 * calling the involved module via modulename_get_completion_state() to check
469 * module-specific conditions.
471 * @param stdClass|cm_info $cm Course-module
472 * @param int $possibleresult Expected completion result. If the event that
473 * has just occurred (e.g. add post) can only result in making the activity
474 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
475 * has just occurred (e.g. delete post) can only result in making the activity
476 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
477 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
478 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
479 * processing early if the user's completion state already matches the expected
480 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
481 * must be used; these directly set the specified state.
482 * @param int $userid User ID to be updated. Default 0 = current user
485 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
486 global $USER, $SESSION;
488 // Do nothing if completion is not enabled for that activity
489 if (!$this->is_enabled($cm)) {
493 // Get current value of completion state and do nothing if it's same as
494 // the possible result of this change. If the change is to COMPLETE and the
495 // current value is one of the COMPLETE_xx subtypes, ignore that as well
496 $current = $this->get_data($cm, false, $userid);
497 if ($possibleresult == $current->completionstate ||
498 ($possibleresult == COMPLETION_COMPLETE &&
499 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
500 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
504 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
505 // For manual tracking we set the result directly
506 switch($possibleresult) {
507 case COMPLETION_COMPLETE:
508 case COMPLETION_INCOMPLETE:
509 $newstate = $possibleresult;
512 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
516 // Automatic tracking; get new state
517 $newstate = $this->internal_get_state($cm, $userid, $current);
520 // If changed, update
521 if ($newstate != $current->completionstate) {
522 $current->completionstate = $newstate;
523 $current->timemodified = time();
524 $this->internal_set_data($cm, $current);
529 * Calculates the completion state for an activity and user.
531 * Internal function. Not private, so we can unit-test it.
533 * @param stdClass|cm_info $cm Activity
534 * @param int $userid ID of user
535 * @param stdClass $current Previous completion information from database
538 public function internal_get_state($cm, $userid, $current) {
539 global $USER, $DB, $CFG;
547 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
548 $current->viewed == COMPLETION_NOT_VIEWED) {
550 return COMPLETION_INCOMPLETE;
553 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
554 if (!isset($cm->modname)) {
555 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
558 $newstate = COMPLETION_COMPLETE;
561 if (!is_null($cm->completiongradeitemnumber)) {
562 require_once($CFG->libdir.'/gradelib.php');
563 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
564 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
565 'itemnumber'=>$cm->completiongradeitemnumber));
567 // Fetch 'grades' (will be one or none)
568 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
569 if (empty($grades)) {
571 return COMPLETION_INCOMPLETE;
573 if (count($grades) > 1) {
574 $this->internal_systemerror("Unexpected result: multiple grades for
575 item '{$item->id}', user '{$userid}'");
577 $newstate = self::internal_get_grade_state($item, reset($grades));
578 if ($newstate == COMPLETION_INCOMPLETE) {
579 return COMPLETION_INCOMPLETE;
583 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
584 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
588 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
589 $function = $cm->modname.'_get_completion_state';
590 if (!function_exists($function)) {
591 $this->internal_systemerror("Module {$cm->modname} claims to support
592 FEATURE_COMPLETION_HAS_RULES but does not have required
593 {$cm->modname}_get_completion_state function");
595 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
596 return COMPLETION_INCOMPLETE;
605 * Marks a module as viewed.
607 * Should be called whenever a module is 'viewed' (it is up to the module how to
608 * determine that). Has no effect if viewing is not set as a completion condition.
610 * Note that this function must be called before you print the page header because
611 * it is possible that the navigation block may depend on it. If you call it after
612 * printing the header, it shows a developer debug warning.
614 * @param stdClass|cm_info $cm Activity
615 * @param int $userid User ID or 0 (default) for current user
618 public function set_module_viewed($cm, $userid=0) {
619 global $PAGE, $UNITTEST;
620 if ($PAGE->headerprinted && empty($UNITTEST->running)) {
621 debugging('set_module_viewed must be called before header is printed',
624 // Don't do anything if view condition is not turned on
625 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
628 // Get current completion state
629 $data = $this->get_data($cm, $userid);
630 // If we already viewed it, don't do anything
631 if ($data->viewed == COMPLETION_VIEWED) {
634 // OK, change state, save it, and update completion
635 $data->viewed = COMPLETION_VIEWED;
636 $this->internal_set_data($cm, $data);
637 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
641 * Determines how much completion data exists for an activity. This is used when
642 * deciding whether completion information should be 'locked' in the module
645 * @param cm_info $cm Activity
646 * @return int The number of users who have completion data stored for this
647 * activity, 0 if none
649 public function count_user_data($cm) {
652 return $DB->get_field_sql("
656 {course_modules_completion}
658 coursemoduleid=? AND completionstate<>0", array($cm->id));
662 * Determines how much course completion data exists for a course. This is used when
663 * deciding whether completion information should be 'locked' in the completion
664 * settings form and activity completion settings.
666 * @param int $user_id Optionally only get course completion data for a single user
667 * @return int The number of users who have completion data stored for this
670 public function count_course_user_data($user_id = null) {
677 {course_completion_crit_compl}
682 $params = array($this->course_id);
684 // Limit data to a single user if an ID is supplied
686 $sql .= ' AND userid = ?';
687 $params[] = $user_id;
690 return $DB->get_field_sql($sql, $params);
694 * Check if this course's completion criteria should be locked
698 public function is_course_locked() {
699 return (bool) $this->count_course_user_data();
703 * Deletes all course completion completion data.
705 * Intended to be used when unlocking completion criteria settings.
707 public function delete_course_completion_data() {
710 $DB->delete_records('course_completions', array('course' => $this->course_id));
711 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
715 * Deletes all activity and course completion data for an entire course
716 * (the below delete_all_state function does this for a single activity).
718 * Used by course reset page.
720 public function delete_all_completion_data() {
721 global $DB, $SESSION;
723 // Delete from database.
724 $DB->delete_records_select('course_modules_completion',
725 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
726 array($this->course_id));
728 // Reset cache for current user.
729 if (isset($SESSION->completioncache) &&
730 array_key_exists($this->course_id, $SESSION->completioncache)) {
732 unset($SESSION->completioncache[$this->course_id]);
735 // Wipe course completion data too.
736 $this->delete_course_completion_data();
740 * Deletes completion state related to an activity for all users.
742 * Intended for use only when the activity itself is deleted.
744 * @param stdClass|cm_info $cm Activity
746 public function delete_all_state($cm) {
747 global $SESSION, $DB;
749 // Delete from database
750 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
752 // Erase cache data for current user if applicable
753 if (isset($SESSION->completioncache) &&
754 array_key_exists($cm->course, $SESSION->completioncache) &&
755 array_key_exists($cm->id, $SESSION->completioncache[$cm->course])) {
757 unset($SESSION->completioncache[$cm->course][$cm->id]);
760 // Check if there is an associated course completion criteria
761 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
763 foreach ($criteria as $criterion) {
764 if ($criterion->moduleinstance == $cm->id) {
765 $acriteria = $criterion;
771 // Delete all criteria completions relating to this activity
772 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
773 $DB->delete_records('course_completions', array('course' => $this->course_id));
778 * Recalculates completion state related to an activity for all users.
780 * Intended for use if completion conditions change. (This should be avoided
781 * as it may cause some things to become incomplete when they were previously
782 * complete, with the effect - for example - of hiding a later activity that
783 * was previously available.)
785 * Resetting state of manual tickbox has same result as deleting state for
788 * @param stcClass|cm_info $cm Activity
790 public function reset_all_state($cm) {
793 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
794 $this->delete_all_state($cm);
797 // Get current list of users with completion state
798 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
799 $keepusers = array();
800 foreach ($rs as $rec) {
801 $keepusers[] = $rec->userid;
805 // Delete all existing state [also clears session cache for current user]
806 $this->delete_all_state($cm);
808 // Merge this with list of planned users (according to roles)
809 $trackedusers = $this->get_tracked_users();
810 foreach ($trackedusers as $trackeduser) {
811 $keepusers[] = $trackeduser->id;
813 $keepusers = array_unique($keepusers);
815 // Recalculate state for each kept user
816 foreach ($keepusers as $keepuser) {
817 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
822 * Obtains completion data for a particular activity and user (from the
823 * session cache if available, or by SQL query)
825 * @param stcClass|cm_info $cm Activity; only required field is ->id
826 * @param bool $wholecourse If true (default false) then, when necessary to
827 * fill the cache, retrieves information from the entire course not just for
829 * @param int $userid User ID or 0 (default) for current user
830 * @param array $modinfo Supply the value here - this is used for unit
831 * testing and so that it can be called recursively from within
832 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
833 * Otherwise the method calls get_fast_modinfo itself.
834 * @return object Completion data (record from course_modules_completion)
836 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
837 global $USER, $CFG, $SESSION, $DB;
844 // Is this the current user?
845 $currentuser = $userid==$USER->id;
847 if ($currentuser && is_object($SESSION)) {
848 // Make sure cache is present and is for current user (loginas
850 if (!isset($SESSION->completioncache) || $SESSION->completioncacheuserid!=$USER->id) {
851 $SESSION->completioncache = array();
852 $SESSION->completioncacheuserid = $USER->id;
854 // Expire any old data from cache
855 foreach ($SESSION->completioncache as $courseid=>$activities) {
856 if (empty($activities['updated']) || $activities['updated'] < time()-COMPLETION_CACHE_EXPIRY) {
857 unset($SESSION->completioncache[$courseid]);
860 // See if requested data is present, if so use cache to get it
861 if (isset($SESSION->completioncache) &&
862 array_key_exists($this->course->id, $SESSION->completioncache) &&
863 array_key_exists($cm->id, $SESSION->completioncache[$this->course->id])) {
864 return $SESSION->completioncache[$this->course->id][$cm->id];
868 // Not there, get via SQL
869 if ($currentuser && $wholecourse) {
870 // Get whole course data for cache
871 $alldatabycmc = $DB->get_records_sql("
876 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
878 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
883 foreach ($alldatabycmc as $data) {
884 $alldata[$data->coursemoduleid] = $data;
888 // Get the module info and build up condition info for each one
889 if (empty($modinfo)) {
890 $modinfo = get_fast_modinfo($this->course, $userid);
892 foreach ($modinfo->cms as $othercm) {
893 if (array_key_exists($othercm->id, $alldata)) {
894 $data = $alldata[$othercm->id];
896 // Row not present counts as 'not complete'
897 $data = new StdClass;
899 $data->coursemoduleid = $othercm->id;
900 $data->userid = $userid;
901 $data->completionstate = 0;
903 $data->timemodified = 0;
905 $SESSION->completioncache[$this->course->id][$othercm->id] = $data;
907 $SESSION->completioncache[$this->course->id]['updated'] = time();
909 if (!isset($SESSION->completioncache[$this->course->id][$cm->id])) {
910 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
912 return $SESSION->completioncache[$this->course->id][$cm->id];
916 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
917 if ($data == false) {
918 // Row not present counts as 'not complete'
919 $data = new StdClass;
921 $data->coursemoduleid = $cm->id;
922 $data->userid = $userid;
923 $data->completionstate = 0;
925 $data->timemodified = 0;
930 $SESSION->completioncache[$this->course->id][$cm->id] = $data;
931 // For single updates, only set date if it was empty before
932 if (empty($SESSION->completioncache[$this->course->id]['updated'])) {
933 $SESSION->completioncache[$this->course->id]['updated'] = time();
942 * Updates completion data for a particular coursemodule and user (user is
943 * determined from $data).
945 * (Internal function. Not private, so we can unit-test it.)
947 * @param stdClass|cm_info $cm Activity
948 * @param stdClass $data Data about completion for that user
950 public function internal_set_data($cm, $data) {
951 global $USER, $SESSION, $DB;
953 $transaction = $DB->start_delegated_transaction();
955 // Check there isn't really a row
956 $data->id = $DB->get_field('course_modules_completion', 'id',
957 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
960 // Didn't exist before, needs creating
961 $data->id = $DB->insert_record('course_modules_completion', $data);
963 // Has real (nonzero) id meaning that a database row exists, update
964 $DB->update_record('course_modules_completion', $data);
966 $transaction->allow_commit();
968 if ($data->userid == $USER->id) {
969 $SESSION->completioncache[$cm->course][$cm->id] = $data;
971 get_fast_modinfo($reset);
976 * Obtains a list of activities for which completion is enabled on the
977 * course. The list is ordered by the section order of those activities.
979 * @param array $modinfo For unit testing only, supply the value
980 * here. Otherwise the method calls get_fast_modinfo
981 * @return array Array from $cmid => $cm of all activities with completion enabled,
982 * empty array if none
984 public function get_activities($modinfo=null) {
987 // Obtain those activities which have completion turned on
988 $withcompletion = $DB->get_records_select('course_modules', 'course='.$this->course->id.
989 ' AND completion<>'.COMPLETION_TRACKING_NONE);
990 if (!$withcompletion) {
994 // Use modinfo to get section order and also add in names
995 if (empty($modinfo)) {
996 $modinfo = get_fast_modinfo($this->course);
999 foreach ($modinfo->sections as $sectioncms) {
1000 foreach ($sectioncms as $cmid) {
1001 if (array_key_exists($cmid, $withcompletion)) {
1002 $result[$cmid] = $withcompletion[$cmid];
1003 $result[$cmid]->modname = $modinfo->cms[$cmid]->modname;
1004 $result[$cmid]->name = $modinfo->cms[$cmid]->name;
1013 * Checks to see if the userid supplied has a tracked role in
1016 * @param int $userid User id
1019 public function is_tracked_user($userid) {
1020 return is_enrolled(context_course::instance($this->course->id), $userid, '', true);
1024 * Returns the number of users whose progress is tracked in this course.
1026 * Optionally supply a search's where clause, or a group id.
1028 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1029 * @param array $whereparams Where clause params
1030 * @param int $groupid Group id
1031 * @return int Number of tracked users
1033 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1036 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1037 context_course::instance($this->course->id), '', $groupid, true);
1038 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1040 $sql .= " WHERE $where";
1043 $params = array_merge($enrolledparams, $whereparams);
1044 return $DB->count_records_sql($sql, $params);
1048 * Return array of users whose progress is tracked in this course.
1050 * Optionally supply a search's where clause, group id, sorting, paging.
1052 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1053 * @param array $whereparams Where clause params (optional)
1054 * @param int $groupid Group ID to restrict to (optional)
1055 * @param string $sort Order by clause (optional)
1056 * @param int $limitfrom Result start (optional)
1057 * @param int $limitnum Result max size (optional)
1058 * @param context $extracontext If set, includes extra user information fields
1059 * as appropriate to display for current user in this context
1060 * @return array Array of user objects with standard user fields
1062 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1063 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1067 list($enrolledsql, $params) = get_enrolled_sql(
1068 context_course::instance($this->course->id), '', $groupid, true);
1070 $sql = 'SELECT u.id, u.firstname, u.lastname, u.idnumber';
1071 if ($extracontext) {
1072 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1074 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1077 $sql .= " AND $where";
1078 $params = array_merge($params, $whereparams);
1082 $sql .= " ORDER BY $sort";
1085 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1089 * Obtains progress information across a course for all users on that course, or
1090 * for all users in a specific group. Intended for use when displaying progress.
1092 * This includes only users who, in course context, have one of the roles for
1093 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1095 * Users are included (in the first array) even if they do not have
1096 * completion progress for any course-module.
1098 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1100 * @param string $where Where clause sql (optional)
1101 * @param array $where_params Where clause params (optional)
1102 * @param int $groupid Group ID or 0 (default)/false for all groups
1103 * @param int $pagesize Number of users to actually return (optional)
1104 * @param int $start User to start at if paging (optional)
1105 * @param context $extracontext If set, includes extra user information fields
1106 * as appropriate to display for current user in this context
1107 * @return stdClass with ->total and ->start (same as $start) and ->users;
1108 * an array of user objects (like mdl_user id, firstname, lastname)
1109 * containing an additional ->progress array of coursemoduleid => completionstate
1111 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1112 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1115 // Get list of applicable users
1116 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1117 $start, $pagesize, $extracontext);
1119 // Get progress information for these users in groups of 1, 000 (if needed)
1120 // to avoid making the SQL IN too long
1123 foreach ($users as $user) {
1124 $userids[] = $user->id;
1125 $results[$user->id] = $user;
1126 $results[$user->id]->progress = array();
1129 for($i=0; $i<count($userids); $i+=1000) {
1130 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1132 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1133 array_splice($params, 0, 0, array($this->course->id));
1134 $rs = $DB->get_recordset_sql("
1139 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1141 cm.course=? AND cmc.userid $insql", $params);
1142 foreach ($rs as $progress) {
1143 $progress = (object)$progress;
1144 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1153 * Called by grade code to inform the completion system when a grade has
1154 * been changed. If the changed grade is used to determine completion for
1155 * the course-module, then the completion status will be updated.
1157 * @param stdClass|cm_info $cm Course-module for item that owns grade
1158 * @param grade_item $item Grade item
1159 * @param stdClass $grade
1160 * @param bool $deleted
1162 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1163 // Bail out now if completion is not enabled for course-module, it is enabled
1164 // but is set to manual, grade is not used to compute completion, or this
1165 // is a different numbered grade
1166 if (!$this->is_enabled($cm) ||
1167 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1168 is_null($cm->completiongradeitemnumber) ||
1169 $item->itemnumber != $cm->completiongradeitemnumber) {
1173 // What is the expected result based on this grade?
1175 // Grade being deleted, so only change could be to make it incomplete
1176 $possibleresult = COMPLETION_INCOMPLETE;
1178 $possibleresult = self::internal_get_grade_state($item, $grade);
1181 // OK, let's update state based on this
1182 $this->update_state($cm, $possibleresult, $grade->userid);
1186 * Calculates the completion state that would result from a graded item
1187 * (where grade-based completion is turned on) based on the actual grade
1190 * Internal function. Not private, so we can unit-test it.
1192 * @param grade_item $item an instance of grade_item
1193 * @param grade_grade $grade an instance of grade_grade
1194 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1196 public static function internal_get_grade_state($item, $grade) {
1198 return COMPLETION_INCOMPLETE;
1200 // Conditions to show pass/fail:
1201 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1202 // b) Grade is visible (neither hidden nor hidden-until)
1203 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1204 // Use final grade if set otherwise raw grade
1205 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1207 // We are displaying and tracking pass/fail
1208 if ($score >= $item->gradepass) {
1209 return COMPLETION_COMPLETE_PASS;
1211 return COMPLETION_COMPLETE_FAIL;
1214 // Not displaying pass/fail, so just if there is a grade
1215 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1216 // Grade exists, so maybe complete now
1217 return COMPLETION_COMPLETE;
1219 // Grade does not exist, so maybe incomplete now
1220 return COMPLETION_INCOMPLETE;
1226 * Aggregate activity completion state
1228 * @param int $type Aggregation type (COMPLETION_* constant)
1229 * @param bool $old Old state
1230 * @param bool $new New state
1233 public static function aggregate_completion_states($type, $old, $new) {
1234 if ($type == COMPLETION_AND) {
1235 return $old && $new;
1237 return $old || $new;
1242 * This is to be used only for system errors (things that shouldn't happen)
1243 * and not user-level errors.
1246 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1247 * @throws moodle_exception Exception with the error string as debug info
1249 public function internal_systemerror($error) {
1251 throw new moodle_exception('err_system','completion',
1252 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1256 * For testing only. Wipes information cached in user session.
1258 public static function wipe_session_cache() {
1260 unset($SESSION->completioncache);
1261 unset($SESSION->completioncacheuserid);