Merge branch 'MDL-62560-master'
[moodle.git] / lib / completionlib.php
blob3d8a5e726137e569176c69ae360d23518a8a6752
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 $criteria = $this->get_criteria($criteriatype);
361 $completions = array();
363 foreach ($criteria as $criterion) {
364 $params = array(
365 'course' => $this->course_id,
366 'userid' => $user_id,
367 'criteriaid' => $criterion->id
370 $completion = new completion_criteria_completion($params);
371 $completion->attach_criteria($criterion);
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 * Check whether the supplied user can override the activity completion statuses within the current course.
525 * @param stdClass $user The user object.
526 * @return bool True if the user can override, false otherwise.
528 public function user_can_override_completion($user) {
529 return has_capability('moodle/course:overridecompletion', context_course::instance($this->course_id), $user);
533 * Updates (if necessary) the completion state of activity $cm for the given
534 * user.
536 * For manual completion, this function is called when completion is toggled
537 * with $possibleresult set to the target state.
539 * For automatic completion, this function should be called every time a module
540 * does something which might influence a user's completion state. For example,
541 * if a forum provides options for marking itself 'completed' once a user makes
542 * N posts, this function should be called every time a user makes a new post.
543 * [After the post has been saved to the database]. When calling, you do not
544 * need to pass in the new completion state. Instead this function carries out
545 * completion calculation by checking grades and viewed state itself, and
546 * calling the involved module via modulename_get_completion_state() to check
547 * module-specific conditions.
549 * @param stdClass|cm_info $cm Course-module
550 * @param int $possibleresult Expected completion result. If the event that
551 * has just occurred (e.g. add post) can only result in making the activity
552 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
553 * has just occurred (e.g. delete post) can only result in making the activity
554 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
555 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
556 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
557 * processing early if the user's completion state already matches the expected
558 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
559 * must be used; these directly set the specified state.
560 * @param int $userid User ID to be updated. Default 0 = current user
561 * @param bool $override Whether manually overriding the existing completion state.
562 * @return void
563 * @throws moodle_exception if trying to override without permission.
565 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0, $override = false) {
566 global $USER;
568 // Do nothing if completion is not enabled for that activity
569 if (!$this->is_enabled($cm)) {
570 return;
573 // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
574 if ($override) {
575 if (!$this->user_can_override_completion($USER)) {
576 throw new required_capability_exception(context_course::instance($this->course_id),
577 'moodle/course:overridecompletion', 'nopermission', '');
581 // Get current value of completion state and do nothing if it's same as
582 // the possible result of this change. If the change is to COMPLETE and the
583 // current value is one of the COMPLETE_xx subtypes, ignore that as well
584 $current = $this->get_data($cm, false, $userid);
585 if ($possibleresult == $current->completionstate ||
586 ($possibleresult == COMPLETION_COMPLETE &&
587 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
588 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
589 return;
592 // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
593 // unless processing another override.
594 // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
595 // overridden to INCOMPLETE to still be processed by normal completion triggers.
596 if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC && !is_null($current->overrideby)
597 && $current->completionstate == COMPLETION_COMPLETE && !$override) {
598 return;
601 // For manual tracking, or if overriding the completion state, we set the state directly.
602 if ($cm->completion == COMPLETION_TRACKING_MANUAL || $override) {
603 switch($possibleresult) {
604 case COMPLETION_COMPLETE:
605 case COMPLETION_INCOMPLETE:
606 $newstate = $possibleresult;
607 break;
608 default:
609 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
612 } else {
613 $newstate = $this->internal_get_state($cm, $userid, $current);
616 // If changed, update
617 if ($newstate != $current->completionstate) {
618 $current->completionstate = $newstate;
619 $current->timemodified = time();
620 $current->overrideby = $override ? $USER->id : null;
621 $this->internal_set_data($cm, $current);
626 * Calculates the completion state for an activity and user.
628 * Internal function. Not private, so we can unit-test it.
630 * @param stdClass|cm_info $cm Activity
631 * @param int $userid ID of user
632 * @param stdClass $current Previous completion information from database
633 * @return mixed
635 public function internal_get_state($cm, $userid, $current) {
636 global $USER, $DB, $CFG;
638 // Get user ID
639 if (!$userid) {
640 $userid = $USER->id;
643 // Check viewed
644 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
645 $current->viewed == COMPLETION_NOT_VIEWED) {
647 return COMPLETION_INCOMPLETE;
650 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
651 if (!isset($cm->modname)) {
652 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
655 $newstate = COMPLETION_COMPLETE;
657 // Check grade
658 if (!is_null($cm->completiongradeitemnumber)) {
659 require_once($CFG->libdir.'/gradelib.php');
660 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
661 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
662 'itemnumber'=>$cm->completiongradeitemnumber));
663 if ($item) {
664 // Fetch 'grades' (will be one or none)
665 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
666 if (empty($grades)) {
667 // No grade for user
668 return COMPLETION_INCOMPLETE;
670 if (count($grades) > 1) {
671 $this->internal_systemerror("Unexpected result: multiple grades for
672 item '{$item->id}', user '{$userid}'");
674 $newstate = self::internal_get_grade_state($item, reset($grades));
675 if ($newstate == COMPLETION_INCOMPLETE) {
676 return COMPLETION_INCOMPLETE;
679 } else {
680 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
681 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
685 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
686 $function = $cm->modname.'_get_completion_state';
687 if (!function_exists($function)) {
688 $this->internal_systemerror("Module {$cm->modname} claims to support
689 FEATURE_COMPLETION_HAS_RULES but does not have required
690 {$cm->modname}_get_completion_state function");
692 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
693 return COMPLETION_INCOMPLETE;
697 return $newstate;
702 * Marks a module as viewed.
704 * Should be called whenever a module is 'viewed' (it is up to the module how to
705 * determine that). Has no effect if viewing is not set as a completion condition.
707 * Note that this function must be called before you print the page header because
708 * it is possible that the navigation block may depend on it. If you call it after
709 * printing the header, it shows a developer debug warning.
711 * @param stdClass|cm_info $cm Activity
712 * @param int $userid User ID or 0 (default) for current user
713 * @return void
715 public function set_module_viewed($cm, $userid=0) {
716 global $PAGE;
717 if ($PAGE->headerprinted) {
718 debugging('set_module_viewed must be called before header is printed',
719 DEBUG_DEVELOPER);
722 // Don't do anything if view condition is not turned on
723 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
724 return;
727 // Get current completion state
728 $data = $this->get_data($cm, false, $userid);
730 // If we already viewed it, don't do anything unless the completion status is overridden.
731 // If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
732 if ($data->viewed == COMPLETION_VIEWED && empty($data->overrideby)) {
733 return;
736 // OK, change state, save it, and update completion
737 $data->viewed = COMPLETION_VIEWED;
738 $this->internal_set_data($cm, $data);
739 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
743 * Determines how much completion data exists for an activity. This is used when
744 * deciding whether completion information should be 'locked' in the module
745 * editing form.
747 * @param cm_info $cm Activity
748 * @return int The number of users who have completion data stored for this
749 * activity, 0 if none
751 public function count_user_data($cm) {
752 global $DB;
754 return $DB->get_field_sql("
755 SELECT
756 COUNT(1)
757 FROM
758 {course_modules_completion}
759 WHERE
760 coursemoduleid=? AND completionstate<>0", array($cm->id));
764 * Determines how much course completion data exists for a course. This is used when
765 * deciding whether completion information should be 'locked' in the completion
766 * settings form and activity completion settings.
768 * @param int $user_id Optionally only get course completion data for a single user
769 * @return int The number of users who have completion data stored for this
770 * course, 0 if none
772 public function count_course_user_data($user_id = null) {
773 global $DB;
775 $sql = '
776 SELECT
777 COUNT(1)
778 FROM
779 {course_completion_crit_compl}
780 WHERE
781 course = ?
784 $params = array($this->course_id);
786 // Limit data to a single user if an ID is supplied
787 if ($user_id) {
788 $sql .= ' AND userid = ?';
789 $params[] = $user_id;
792 return $DB->get_field_sql($sql, $params);
796 * Check if this course's completion criteria should be locked
798 * @return boolean
800 public function is_course_locked() {
801 return (bool) $this->count_course_user_data();
805 * Deletes all course completion completion data.
807 * Intended to be used when unlocking completion criteria settings.
809 public function delete_course_completion_data() {
810 global $DB;
812 $DB->delete_records('course_completions', array('course' => $this->course_id));
813 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
815 // Difficult to find affected users, just purge all completion cache.
816 cache::make('core', 'completion')->purge();
817 cache::make('core', 'coursecompletion')->purge();
821 * Deletes all activity and course completion data for an entire course
822 * (the below delete_all_state function does this for a single activity).
824 * Used by course reset page.
826 public function delete_all_completion_data() {
827 global $DB;
829 // Delete from database.
830 $DB->delete_records_select('course_modules_completion',
831 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
832 array($this->course_id));
834 // Wipe course completion data too.
835 $this->delete_course_completion_data();
839 * Deletes completion state related to an activity for all users.
841 * Intended for use only when the activity itself is deleted.
843 * @param stdClass|cm_info $cm Activity
845 public function delete_all_state($cm) {
846 global $DB;
848 // Delete from database
849 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
851 // Check if there is an associated course completion criteria
852 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
853 $acriteria = false;
854 foreach ($criteria as $criterion) {
855 if ($criterion->moduleinstance == $cm->id) {
856 $acriteria = $criterion;
857 break;
861 if ($acriteria) {
862 // Delete all criteria completions relating to this activity
863 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
864 $DB->delete_records('course_completions', array('course' => $this->course_id));
867 // Difficult to find affected users, just purge all completion cache.
868 cache::make('core', 'completion')->purge();
869 cache::make('core', 'coursecompletion')->purge();
873 * Recalculates completion state related to an activity for all users.
875 * Intended for use if completion conditions change. (This should be avoided
876 * as it may cause some things to become incomplete when they were previously
877 * complete, with the effect - for example - of hiding a later activity that
878 * was previously available.)
880 * Resetting state of manual tickbox has same result as deleting state for
881 * it.
883 * @param stcClass|cm_info $cm Activity
885 public function reset_all_state($cm) {
886 global $DB;
888 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
889 $this->delete_all_state($cm);
890 return;
892 // Get current list of users with completion state
893 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
894 $keepusers = array();
895 foreach ($rs as $rec) {
896 $keepusers[] = $rec->userid;
898 $rs->close();
900 // Delete all existing state.
901 $this->delete_all_state($cm);
903 // Merge this with list of planned users (according to roles)
904 $trackedusers = $this->get_tracked_users();
905 foreach ($trackedusers as $trackeduser) {
906 $keepusers[] = $trackeduser->id;
908 $keepusers = array_unique($keepusers);
910 // Recalculate state for each kept user
911 foreach ($keepusers as $keepuser) {
912 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
917 * Obtains completion data for a particular activity and user (from the
918 * completion cache if available, or by SQL query)
920 * @param stcClass|cm_info $cm Activity; only required field is ->id
921 * @param bool $wholecourse If true (default false) then, when necessary to
922 * fill the cache, retrieves information from the entire course not just for
923 * this one activity
924 * @param int $userid User ID or 0 (default) for current user
925 * @param array $modinfo Supply the value here - this is used for unit
926 * testing and so that it can be called recursively from within
927 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
928 * Otherwise the method calls get_fast_modinfo itself.
929 * @return object Completion data (record from course_modules_completion)
931 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
932 global $USER, $CFG, $DB;
933 $completioncache = cache::make('core', 'completion');
935 // Get user ID
936 if (!$userid) {
937 $userid = $USER->id;
940 // See if requested data is present in cache (use cache for current user only).
941 $usecache = $userid == $USER->id;
942 $cacheddata = array();
943 if ($usecache) {
944 $key = $userid . '_' . $this->course->id;
945 if (!isset($this->course->cacherev)) {
946 $this->course = get_course($this->course_id);
948 if ($cacheddata = $completioncache->get($key)) {
949 if ($cacheddata['cacherev'] != $this->course->cacherev) {
950 // Course structure has been changed since the last caching, forget the cache.
951 $cacheddata = array();
952 } else if (isset($cacheddata[$cm->id])) {
953 return (object)$cacheddata[$cm->id];
958 // Not there, get via SQL
959 if ($usecache && $wholecourse) {
960 // Get whole course data for cache
961 $alldatabycmc = $DB->get_records_sql("
962 SELECT
963 cmc.*
964 FROM
965 {course_modules} cm
966 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
967 WHERE
968 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
970 // Reindex by cm id
971 $alldata = array();
972 foreach ($alldatabycmc as $data) {
973 $alldata[$data->coursemoduleid] = (array)$data;
976 // Get the module info and build up condition info for each one
977 if (empty($modinfo)) {
978 $modinfo = get_fast_modinfo($this->course, $userid);
980 foreach ($modinfo->cms as $othercm) {
981 if (isset($alldata[$othercm->id])) {
982 $data = $alldata[$othercm->id];
983 } else {
984 // Row not present counts as 'not complete'
985 $data = array();
986 $data['id'] = 0;
987 $data['coursemoduleid'] = $othercm->id;
988 $data['userid'] = $userid;
989 $data['completionstate'] = 0;
990 $data['viewed'] = 0;
991 $data['overrideby'] = null;
992 $data['timemodified'] = 0;
994 $cacheddata[$othercm->id] = $data;
997 if (!isset($cacheddata[$cm->id])) {
998 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
1001 } else {
1002 // Get single record
1003 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
1004 if ($data) {
1005 $data = (array)$data;
1006 } else {
1007 // Row not present counts as 'not complete'
1008 $data = array();
1009 $data['id'] = 0;
1010 $data['coursemoduleid'] = $cm->id;
1011 $data['userid'] = $userid;
1012 $data['completionstate'] = 0;
1013 $data['viewed'] = 0;
1014 $data['overrideby'] = null;
1015 $data['timemodified'] = 0;
1018 // Put in cache
1019 $cacheddata[$cm->id] = $data;
1022 if ($usecache) {
1023 $cacheddata['cacherev'] = $this->course->cacherev;
1024 $completioncache->set($key, $cacheddata);
1026 return (object)$cacheddata[$cm->id];
1030 * Updates completion data for a particular coursemodule and user (user is
1031 * determined from $data).
1033 * (Internal function. Not private, so we can unit-test it.)
1035 * @param stdClass|cm_info $cm Activity
1036 * @param stdClass $data Data about completion for that user
1038 public function internal_set_data($cm, $data) {
1039 global $USER, $DB;
1041 $transaction = $DB->start_delegated_transaction();
1042 if (!$data->id) {
1043 // Check there isn't really a row
1044 $data->id = $DB->get_field('course_modules_completion', 'id',
1045 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1047 if (!$data->id) {
1048 // Didn't exist before, needs creating
1049 $data->id = $DB->insert_record('course_modules_completion', $data);
1050 } else {
1051 // Has real (nonzero) id meaning that a database row exists, update
1052 $DB->update_record('course_modules_completion', $data);
1054 $transaction->allow_commit();
1056 $cmcontext = context_module::instance($data->coursemoduleid, MUST_EXIST);
1057 $coursecontext = $cmcontext->get_parent_context();
1059 $completioncache = cache::make('core', 'completion');
1060 if ($data->userid == $USER->id) {
1061 // Update module completion in user's cache.
1062 if (!($cachedata = $completioncache->get($data->userid . '_' . $cm->course))
1063 || $cachedata['cacherev'] != $this->course->cacherev) {
1064 $cachedata = array('cacherev' => $this->course->cacherev);
1066 $cachedata[$cm->id] = $data;
1067 $completioncache->set($data->userid . '_' . $cm->course, $cachedata);
1069 // reset modinfo for user (no need to call rebuild_course_cache())
1070 get_fast_modinfo($cm->course, 0, true);
1071 } else {
1072 // Remove another user's completion cache for this course.
1073 $completioncache->delete($data->userid . '_' . $cm->course);
1076 // Trigger an event for course module completion changed.
1077 $event = \core\event\course_module_completion_updated::create(array(
1078 'objectid' => $data->id,
1079 'context' => $cmcontext,
1080 'relateduserid' => $data->userid,
1081 'other' => array(
1082 'relateduserid' => $data->userid,
1083 'overrideby' => $data->overrideby,
1084 'completionstate' => $data->completionstate
1087 $event->add_record_snapshot('course_modules_completion', $data);
1088 $event->trigger();
1092 * Return whether or not the course has activities with completion enabled.
1094 * @return boolean true when there is at least one activity with completion enabled.
1096 public function has_activities() {
1097 $modinfo = get_fast_modinfo($this->course);
1098 foreach ($modinfo->get_cms() as $cm) {
1099 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1100 return true;
1103 return false;
1107 * Obtains a list of activities for which completion is enabled on the
1108 * course. The list is ordered by the section order of those activities.
1110 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1111 * empty array if none
1113 public function get_activities() {
1114 $modinfo = get_fast_modinfo($this->course);
1115 $result = array();
1116 foreach ($modinfo->get_cms() as $cm) {
1117 if ($cm->completion != COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) {
1118 $result[$cm->id] = $cm;
1121 return $result;
1125 * Checks to see if the userid supplied has a tracked role in
1126 * this course
1128 * @param int $userid User id
1129 * @return bool
1131 public function is_tracked_user($userid) {
1132 return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1136 * Returns the number of users whose progress is tracked in this course.
1138 * Optionally supply a search's where clause, or a group id.
1140 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1141 * @param array $whereparams Where clause params
1142 * @param int $groupid Group id
1143 * @return int Number of tracked users
1145 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1146 global $DB;
1148 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1149 context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1150 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1151 if ($where) {
1152 $sql .= " WHERE $where";
1155 $params = array_merge($enrolledparams, $whereparams);
1156 return $DB->count_records_sql($sql, $params);
1160 * Return array of users whose progress is tracked in this course.
1162 * Optionally supply a search's where clause, group id, sorting, paging.
1164 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1165 * @param array $whereparams Where clause params (optional)
1166 * @param int $groupid Group ID to restrict to (optional)
1167 * @param string $sort Order by clause (optional)
1168 * @param int $limitfrom Result start (optional)
1169 * @param int $limitnum Result max size (optional)
1170 * @param context $extracontext If set, includes extra user information fields
1171 * as appropriate to display for current user in this context
1172 * @return array Array of user objects with standard user fields
1174 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1175 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1177 global $DB;
1179 list($enrolledsql, $params) = get_enrolled_sql(
1180 context_course::instance($this->course->id),
1181 'moodle/course:isincompletionreports', $groupid, true);
1183 $allusernames = get_all_user_name_fields(true, 'u');
1184 $sql = 'SELECT u.id, u.idnumber, ' . $allusernames;
1185 if ($extracontext) {
1186 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1188 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1190 if ($where) {
1191 $sql .= " AND $where";
1192 $params = array_merge($params, $whereparams);
1195 if ($sort) {
1196 $sql .= " ORDER BY $sort";
1199 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1203 * Obtains progress information across a course for all users on that course, or
1204 * for all users in a specific group. Intended for use when displaying progress.
1206 * This includes only users who, in course context, have one of the roles for
1207 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1209 * Users are included (in the first array) even if they do not have
1210 * completion progress for any course-module.
1212 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1213 * last name
1214 * @param string $where Where clause sql (optional)
1215 * @param array $where_params Where clause params (optional)
1216 * @param int $groupid Group ID or 0 (default)/false for all groups
1217 * @param int $pagesize Number of users to actually return (optional)
1218 * @param int $start User to start at if paging (optional)
1219 * @param context $extracontext If set, includes extra user information fields
1220 * as appropriate to display for current user in this context
1221 * @return stdClass with ->total and ->start (same as $start) and ->users;
1222 * an array of user objects (like mdl_user id, firstname, lastname)
1223 * containing an additional ->progress array of coursemoduleid => completionstate
1225 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1226 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1227 global $CFG, $DB;
1229 // Get list of applicable users
1230 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1231 $start, $pagesize, $extracontext);
1233 // Get progress information for these users in groups of 1, 000 (if needed)
1234 // to avoid making the SQL IN too long
1235 $results = array();
1236 $userids = array();
1237 foreach ($users as $user) {
1238 $userids[] = $user->id;
1239 $results[$user->id] = $user;
1240 $results[$user->id]->progress = array();
1243 for($i=0; $i<count($userids); $i+=1000) {
1244 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1246 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1247 array_splice($params, 0, 0, array($this->course->id));
1248 $rs = $DB->get_recordset_sql("
1249 SELECT
1250 cmc.*
1251 FROM
1252 {course_modules} cm
1253 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1254 WHERE
1255 cm.course=? AND cmc.userid $insql", $params);
1256 foreach ($rs as $progress) {
1257 $progress = (object)$progress;
1258 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1260 $rs->close();
1263 return $results;
1267 * Called by grade code to inform the completion system when a grade has
1268 * been changed. If the changed grade is used to determine completion for
1269 * the course-module, then the completion status will be updated.
1271 * @param stdClass|cm_info $cm Course-module for item that owns grade
1272 * @param grade_item $item Grade item
1273 * @param stdClass $grade
1274 * @param bool $deleted
1276 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1277 // Bail out now if completion is not enabled for course-module, it is enabled
1278 // but is set to manual, grade is not used to compute completion, or this
1279 // is a different numbered grade
1280 if (!$this->is_enabled($cm) ||
1281 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1282 is_null($cm->completiongradeitemnumber) ||
1283 $item->itemnumber != $cm->completiongradeitemnumber) {
1284 return;
1287 // What is the expected result based on this grade?
1288 if ($deleted) {
1289 // Grade being deleted, so only change could be to make it incomplete
1290 $possibleresult = COMPLETION_INCOMPLETE;
1291 } else {
1292 $possibleresult = self::internal_get_grade_state($item, $grade);
1295 // OK, let's update state based on this
1296 $this->update_state($cm, $possibleresult, $grade->userid);
1300 * Calculates the completion state that would result from a graded item
1301 * (where grade-based completion is turned on) based on the actual grade
1302 * and settings.
1304 * Internal function. Not private, so we can unit-test it.
1306 * @param grade_item $item an instance of grade_item
1307 * @param grade_grade $grade an instance of grade_grade
1308 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1310 public static function internal_get_grade_state($item, $grade) {
1311 // If no grade is supplied or the grade doesn't have an actual value, then
1312 // this is not complete.
1313 if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1314 return COMPLETION_INCOMPLETE;
1317 // Conditions to show pass/fail:
1318 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1319 // b) Grade is visible (neither hidden nor hidden-until)
1320 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1321 // Use final grade if set otherwise raw grade
1322 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1324 // We are displaying and tracking pass/fail
1325 if ($score >= $item->gradepass) {
1326 return COMPLETION_COMPLETE_PASS;
1327 } else {
1328 return COMPLETION_COMPLETE_FAIL;
1330 } else {
1331 // Not displaying pass/fail, so just if there is a grade
1332 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1333 // Grade exists, so maybe complete now
1334 return COMPLETION_COMPLETE;
1335 } else {
1336 // Grade does not exist, so maybe incomplete now
1337 return COMPLETION_INCOMPLETE;
1343 * Aggregate activity completion state
1345 * @param int $type Aggregation type (COMPLETION_* constant)
1346 * @param bool $old Old state
1347 * @param bool $new New state
1348 * @return bool
1350 public static function aggregate_completion_states($type, $old, $new) {
1351 if ($type == COMPLETION_AND) {
1352 return $old && $new;
1353 } else {
1354 return $old || $new;
1359 * This is to be used only for system errors (things that shouldn't happen)
1360 * and not user-level errors.
1362 * @global type $CFG
1363 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1364 * @throws moodle_exception Exception with the error string as debug info
1366 public function internal_systemerror($error) {
1367 global $CFG;
1368 throw new moodle_exception('err_system','completion',
1369 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);