MDL-70424 auth: Avoid random changes to $CFG->auth
[moodle.git] / lib / completionlib.php
blob2258259f865c5fbfcef12ac8eba357cbe5207f9f
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, $USER;
323 $result = '';
324 if ($this->is_enabled() && !$PAGE->user_is_editing() && $this->is_tracked_user($USER->id) && isloggedin() &&
325 !isguestuser()) {
326 $result .= html_writer::tag('div', get_string('yourprogress','completion') .
327 $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
328 'class' => 'completionprogress'));
330 return $result;
334 * Get a course completion for a user
336 * @param int $user_id User id
337 * @param int $criteriatype Specific criteria type to return
338 * @return bool|completion_criteria_completion returns false on fail
340 public function get_completion($user_id, $criteriatype) {
341 $completions = $this->get_completions($user_id, $criteriatype);
343 if (empty($completions)) {
344 return false;
345 } elseif (count($completions) > 1) {
346 print_error('multipleselfcompletioncriteria', 'completion');
349 return $completions[0];
353 * Get all course criteria's completion objects for a user
355 * @param int $user_id User id
356 * @param int $criteriatype Specific criteria type to return (optional)
357 * @return array
359 public function get_completions($user_id, $criteriatype = null) {
360 $criteria = $this->get_criteria($criteriatype);
362 $completions = array();
364 foreach ($criteria as $criterion) {
365 $params = array(
366 'course' => $this->course_id,
367 'userid' => $user_id,
368 'criteriaid' => $criterion->id
371 $completion = new completion_criteria_completion($params);
372 $completion->attach_criteria($criterion);
374 $completions[] = $completion;
377 return $completions;
381 * Get completion object for a user and a criteria
383 * @param int $user_id User id
384 * @param completion_criteria $criteria Criteria object
385 * @return completion_criteria_completion
387 public function get_user_completion($user_id, $criteria) {
388 $params = array(
389 'course' => $this->course_id,
390 'userid' => $user_id,
391 'criteriaid' => $criteria->id,
394 $completion = new completion_criteria_completion($params);
395 return $completion;
399 * Check if course has completion criteria set
401 * @return bool Returns true if there are criteria
403 public function has_criteria() {
404 $criteria = $this->get_criteria();
406 return (bool) count($criteria);
410 * Get course completion criteria
412 * @param int $criteriatype Specific criteria type to return (optional)
414 public function get_criteria($criteriatype = null) {
416 // Fill cache if empty
417 if (!is_array($this->criteria)) {
418 global $DB;
420 $params = array(
421 'course' => $this->course->id
424 // Load criteria from database
425 $records = (array)$DB->get_records('course_completion_criteria', $params);
427 // Order records so activities are in the same order as they appear on the course view page.
428 if ($records) {
429 $activitiesorder = array_keys(get_fast_modinfo($this->course)->get_cms());
430 usort($records, function ($a, $b) use ($activitiesorder) {
431 $aidx = ($a->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
432 array_search($a->moduleinstance, $activitiesorder) : false;
433 $bidx = ($b->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
434 array_search($b->moduleinstance, $activitiesorder) : false;
435 if ($aidx === false || $bidx === false || $aidx == $bidx) {
436 return 0;
438 return ($aidx < $bidx) ? -1 : 1;
442 // Build array of criteria objects
443 $this->criteria = array();
444 foreach ($records as $record) {
445 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
449 // If after all criteria
450 if ($criteriatype === null) {
451 return $this->criteria;
454 // If we are only after a specific criteria type
455 $criteria = array();
456 foreach ($this->criteria as $criterion) {
458 if ($criterion->criteriatype != $criteriatype) {
459 continue;
462 $criteria[$criterion->id] = $criterion;
465 return $criteria;
469 * Get aggregation method
471 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
472 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
474 public function get_aggregation_method($criteriatype = null) {
475 $params = array(
476 'course' => $this->course_id,
477 'criteriatype' => $criteriatype
480 $aggregation = new completion_aggregation($params);
482 if (!$aggregation->id) {
483 $aggregation->method = COMPLETION_AGGREGATION_ALL;
486 return $aggregation->method;
490 * @deprecated since Moodle 2.8 MDL-46290.
492 public function get_incomplete_criteria() {
493 throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
497 * Clear old course completion criteria
499 public function clear_criteria() {
500 global $DB;
502 // Remove completion criteria records for the course itself, and any records that refer to the course.
503 $select = 'course = :course OR (criteriatype = :type AND courseinstance = :courseinstance)';
504 $params = [
505 'course' => $this->course_id,
506 'type' => COMPLETION_CRITERIA_TYPE_COURSE,
507 'courseinstance' => $this->course_id,
510 $DB->delete_records_select('course_completion_criteria', $select, $params);
511 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
513 $this->delete_course_completion_data();
517 * Has the supplied user completed this course
519 * @param int $user_id User's id
520 * @return boolean
522 public function is_course_complete($user_id) {
523 $params = array(
524 'userid' => $user_id,
525 'course' => $this->course_id
528 $ccompletion = new completion_completion($params);
529 return $ccompletion->is_complete();
533 * Check whether the supplied user can override the activity completion statuses within the current course.
535 * @param stdClass $user The user object.
536 * @return bool True if the user can override, false otherwise.
538 public function user_can_override_completion($user) {
539 return has_capability('moodle/course:overridecompletion', context_course::instance($this->course_id), $user);
543 * Updates (if necessary) the completion state of activity $cm for the given
544 * user.
546 * For manual completion, this function is called when completion is toggled
547 * with $possibleresult set to the target state.
549 * For automatic completion, this function should be called every time a module
550 * does something which might influence a user's completion state. For example,
551 * if a forum provides options for marking itself 'completed' once a user makes
552 * N posts, this function should be called every time a user makes a new post.
553 * [After the post has been saved to the database]. When calling, you do not
554 * need to pass in the new completion state. Instead this function carries out
555 * completion calculation by checking grades and viewed state itself, and
556 * calling the involved module via modulename_get_completion_state() to check
557 * module-specific conditions.
559 * @param stdClass|cm_info $cm Course-module
560 * @param int $possibleresult Expected completion result. If the event that
561 * has just occurred (e.g. add post) can only result in making the activity
562 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
563 * has just occurred (e.g. delete post) can only result in making the activity
564 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
565 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
566 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
567 * processing early if the user's completion state already matches the expected
568 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
569 * must be used; these directly set the specified state.
570 * @param int $userid User ID to be updated. Default 0 = current user
571 * @param bool $override Whether manually overriding the existing completion state.
572 * @return void
573 * @throws moodle_exception if trying to override without permission.
575 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0, $override = false) {
576 global $USER;
578 // Do nothing if completion is not enabled for that activity
579 if (!$this->is_enabled($cm)) {
580 return;
583 // If we're processing an override and the current user isn't allowed to do so, then throw an exception.
584 if ($override) {
585 if (!$this->user_can_override_completion($USER)) {
586 throw new required_capability_exception(context_course::instance($this->course_id),
587 'moodle/course:overridecompletion', 'nopermission', '');
591 // Get current value of completion state and do nothing if it's same as
592 // the possible result of this change. If the change is to COMPLETE and the
593 // current value is one of the COMPLETE_xx subtypes, ignore that as well
594 $current = $this->get_data($cm, false, $userid);
595 if ($possibleresult == $current->completionstate ||
596 ($possibleresult == COMPLETION_COMPLETE &&
597 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
598 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
599 return;
602 // For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
603 // unless processing another override.
604 // Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
605 // overridden to INCOMPLETE to still be processed by normal completion triggers.
606 if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC && !is_null($current->overrideby)
607 && $current->completionstate == COMPLETION_COMPLETE && !$override) {
608 return;
611 // For manual tracking, or if overriding the completion state, we set the state directly.
612 if ($cm->completion == COMPLETION_TRACKING_MANUAL || $override) {
613 switch($possibleresult) {
614 case COMPLETION_COMPLETE:
615 case COMPLETION_INCOMPLETE:
616 $newstate = $possibleresult;
617 break;
618 default:
619 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
622 } else {
623 $newstate = $this->internal_get_state($cm, $userid, $current);
626 // If changed, update
627 if ($newstate != $current->completionstate) {
628 $current->completionstate = $newstate;
629 $current->timemodified = time();
630 $current->overrideby = $override ? $USER->id : null;
631 $this->internal_set_data($cm, $current);
636 * Calculates the completion state for an activity and user.
638 * Internal function. Not private, so we can unit-test it.
640 * @param stdClass|cm_info $cm Activity
641 * @param int $userid ID of user
642 * @param stdClass $current Previous completion information from database
643 * @return mixed
645 public function internal_get_state($cm, $userid, $current) {
646 global $USER, $DB, $CFG;
648 // Get user ID
649 if (!$userid) {
650 $userid = $USER->id;
653 // Check viewed
654 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
655 $current->viewed == COMPLETION_NOT_VIEWED) {
657 return COMPLETION_INCOMPLETE;
660 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
661 if (!isset($cm->modname)) {
662 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
665 $newstate = COMPLETION_COMPLETE;
667 // Check grade
668 if (!is_null($cm->completiongradeitemnumber)) {
669 require_once($CFG->libdir.'/gradelib.php');
670 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
671 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
672 'itemnumber'=>$cm->completiongradeitemnumber));
673 if ($item) {
674 // Fetch 'grades' (will be one or none)
675 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
676 if (empty($grades)) {
677 // No grade for user
678 return COMPLETION_INCOMPLETE;
680 if (count($grades) > 1) {
681 $this->internal_systemerror("Unexpected result: multiple grades for
682 item '{$item->id}', user '{$userid}'");
684 $newstate = self::internal_get_grade_state($item, reset($grades));
685 if ($newstate == COMPLETION_INCOMPLETE) {
686 return COMPLETION_INCOMPLETE;
689 } else {
690 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
691 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
695 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
696 $function = $cm->modname.'_get_completion_state';
697 if (!function_exists($function)) {
698 $this->internal_systemerror("Module {$cm->modname} claims to support
699 FEATURE_COMPLETION_HAS_RULES but does not have required
700 {$cm->modname}_get_completion_state function");
702 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
703 return COMPLETION_INCOMPLETE;
707 return $newstate;
712 * Marks a module as viewed.
714 * Should be called whenever a module is 'viewed' (it is up to the module how to
715 * determine that). Has no effect if viewing is not set as a completion condition.
717 * Note that this function must be called before you print the page header because
718 * it is possible that the navigation block may depend on it. If you call it after
719 * printing the header, it shows a developer debug warning.
721 * @param stdClass|cm_info $cm Activity
722 * @param int $userid User ID or 0 (default) for current user
723 * @return void
725 public function set_module_viewed($cm, $userid=0) {
726 global $PAGE;
727 if ($PAGE->headerprinted) {
728 debugging('set_module_viewed must be called before header is printed',
729 DEBUG_DEVELOPER);
732 // Don't do anything if view condition is not turned on
733 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
734 return;
737 // Get current completion state
738 $data = $this->get_data($cm, false, $userid);
740 // If we already viewed it, don't do anything unless the completion status is overridden.
741 // If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
742 if ($data->viewed == COMPLETION_VIEWED && empty($data->overrideby)) {
743 return;
746 // OK, change state, save it, and update completion
747 $data->viewed = COMPLETION_VIEWED;
748 $this->internal_set_data($cm, $data);
749 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
753 * Determines how much completion data exists for an activity. This is used when
754 * deciding whether completion information should be 'locked' in the module
755 * editing form.
757 * @param cm_info $cm Activity
758 * @return int The number of users who have completion data stored for this
759 * activity, 0 if none
761 public function count_user_data($cm) {
762 global $DB;
764 return $DB->get_field_sql("
765 SELECT
766 COUNT(1)
767 FROM
768 {course_modules_completion}
769 WHERE
770 coursemoduleid=? AND completionstate<>0", array($cm->id));
774 * Determines how much course completion data exists for a course. This is used when
775 * deciding whether completion information should be 'locked' in the completion
776 * settings form and activity completion settings.
778 * @param int $user_id Optionally only get course completion data for a single user
779 * @return int The number of users who have completion data stored for this
780 * course, 0 if none
782 public function count_course_user_data($user_id = null) {
783 global $DB;
785 $sql = '
786 SELECT
787 COUNT(1)
788 FROM
789 {course_completion_crit_compl}
790 WHERE
791 course = ?
794 $params = array($this->course_id);
796 // Limit data to a single user if an ID is supplied
797 if ($user_id) {
798 $sql .= ' AND userid = ?';
799 $params[] = $user_id;
802 return $DB->get_field_sql($sql, $params);
806 * Check if this course's completion criteria should be locked
808 * @return boolean
810 public function is_course_locked() {
811 return (bool) $this->count_course_user_data();
815 * Deletes all course completion completion data.
817 * Intended to be used when unlocking completion criteria settings.
819 public function delete_course_completion_data() {
820 global $DB;
822 $DB->delete_records('course_completions', array('course' => $this->course_id));
823 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
825 // Difficult to find affected users, just purge all completion cache.
826 cache::make('core', 'completion')->purge();
827 cache::make('core', 'coursecompletion')->purge();
831 * Deletes all activity and course completion data for an entire course
832 * (the below delete_all_state function does this for a single activity).
834 * Used by course reset page.
836 public function delete_all_completion_data() {
837 global $DB;
839 // Delete from database.
840 $DB->delete_records_select('course_modules_completion',
841 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
842 array($this->course_id));
844 // Wipe course completion data too.
845 $this->delete_course_completion_data();
849 * Deletes completion state related to an activity for all users.
851 * Intended for use only when the activity itself is deleted.
853 * @param stdClass|cm_info $cm Activity
855 public function delete_all_state($cm) {
856 global $DB;
858 // Delete from database
859 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
861 // Check if there is an associated course completion criteria
862 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
863 $acriteria = false;
864 foreach ($criteria as $criterion) {
865 if ($criterion->moduleinstance == $cm->id) {
866 $acriteria = $criterion;
867 break;
871 if ($acriteria) {
872 // Delete all criteria completions relating to this activity
873 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
874 $DB->delete_records('course_completions', array('course' => $this->course_id));
877 // Difficult to find affected users, just purge all completion cache.
878 cache::make('core', 'completion')->purge();
879 cache::make('core', 'coursecompletion')->purge();
883 * Recalculates completion state related to an activity for all users.
885 * Intended for use if completion conditions change. (This should be avoided
886 * as it may cause some things to become incomplete when they were previously
887 * complete, with the effect - for example - of hiding a later activity that
888 * was previously available.)
890 * Resetting state of manual tickbox has same result as deleting state for
891 * it.
893 * @param stcClass|cm_info $cm Activity
895 public function reset_all_state($cm) {
896 global $DB;
898 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
899 $this->delete_all_state($cm);
900 return;
902 // Get current list of users with completion state
903 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
904 $keepusers = array();
905 foreach ($rs as $rec) {
906 $keepusers[] = $rec->userid;
908 $rs->close();
910 // Delete all existing state.
911 $this->delete_all_state($cm);
913 // Merge this with list of planned users (according to roles)
914 $trackedusers = $this->get_tracked_users();
915 foreach ($trackedusers as $trackeduser) {
916 $keepusers[] = $trackeduser->id;
918 $keepusers = array_unique($keepusers);
920 // Recalculate state for each kept user
921 foreach ($keepusers as $keepuser) {
922 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
927 * Obtains completion data for a particular activity and user (from the
928 * completion cache if available, or by SQL query)
930 * @param stcClass|cm_info $cm Activity; only required field is ->id
931 * @param bool $wholecourse If true (default false) then, when necessary to
932 * fill the cache, retrieves information from the entire course not just for
933 * this one activity
934 * @param int $userid User ID or 0 (default) for current user
935 * @param array $modinfo Supply the value here - this is used for unit
936 * testing and so that it can be called recursively from within
937 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
938 * Otherwise the method calls get_fast_modinfo itself.
939 * @return object Completion data (record from course_modules_completion)
941 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
942 global $USER, $CFG, $DB;
943 $completioncache = cache::make('core', 'completion');
945 // Get user ID
946 if (!$userid) {
947 $userid = $USER->id;
950 // See if requested data is present in cache (use cache for current user only).
951 $usecache = $userid == $USER->id;
952 $cacheddata = array();
953 if ($usecache) {
954 $key = $userid . '_' . $this->course->id;
955 if (!isset($this->course->cacherev)) {
956 $this->course = get_course($this->course_id);
958 if ($cacheddata = $completioncache->get($key)) {
959 if ($cacheddata['cacherev'] != $this->course->cacherev) {
960 // Course structure has been changed since the last caching, forget the cache.
961 $cacheddata = array();
962 } else if (isset($cacheddata[$cm->id])) {
963 return (object)$cacheddata[$cm->id];
968 // Not there, get via SQL
969 if ($usecache && $wholecourse) {
970 // Get whole course data for cache
971 $alldatabycmc = $DB->get_records_sql("
972 SELECT
973 cmc.*
974 FROM
975 {course_modules} cm
976 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
977 WHERE
978 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
980 // Reindex by cm id
981 $alldata = array();
982 foreach ($alldatabycmc as $data) {
983 $alldata[$data->coursemoduleid] = (array)$data;
986 // Get the module info and build up condition info for each one
987 if (empty($modinfo)) {
988 $modinfo = get_fast_modinfo($this->course, $userid);
990 foreach ($modinfo->cms as $othercm) {
991 if (isset($alldata[$othercm->id])) {
992 $data = $alldata[$othercm->id];
993 } else {
994 // Row not present counts as 'not complete'
995 $data = array();
996 $data['id'] = 0;
997 $data['coursemoduleid'] = $othercm->id;
998 $data['userid'] = $userid;
999 $data['completionstate'] = 0;
1000 $data['viewed'] = 0;
1001 $data['overrideby'] = null;
1002 $data['timemodified'] = 0;
1004 $cacheddata[$othercm->id] = $data;
1007 if (!isset($cacheddata[$cm->id])) {
1008 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
1011 } else {
1012 // Get single record
1013 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
1014 if ($data) {
1015 $data = (array)$data;
1016 } else {
1017 // Row not present counts as 'not complete'
1018 $data = array();
1019 $data['id'] = 0;
1020 $data['coursemoduleid'] = $cm->id;
1021 $data['userid'] = $userid;
1022 $data['completionstate'] = 0;
1023 $data['viewed'] = 0;
1024 $data['overrideby'] = null;
1025 $data['timemodified'] = 0;
1028 // Put in cache
1029 $cacheddata[$cm->id] = $data;
1032 if ($usecache) {
1033 $cacheddata['cacherev'] = $this->course->cacherev;
1034 $completioncache->set($key, $cacheddata);
1036 return (object)$cacheddata[$cm->id];
1040 * Updates completion data for a particular coursemodule and user (user is
1041 * determined from $data).
1043 * (Internal function. Not private, so we can unit-test it.)
1045 * @param stdClass|cm_info $cm Activity
1046 * @param stdClass $data Data about completion for that user
1048 public function internal_set_data($cm, $data) {
1049 global $USER, $DB;
1051 $transaction = $DB->start_delegated_transaction();
1052 if (!$data->id) {
1053 // Check there isn't really a row
1054 $data->id = $DB->get_field('course_modules_completion', 'id',
1055 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1057 if (!$data->id) {
1058 // Didn't exist before, needs creating
1059 $data->id = $DB->insert_record('course_modules_completion', $data);
1060 } else {
1061 // Has real (nonzero) id meaning that a database row exists, update
1062 $DB->update_record('course_modules_completion', $data);
1064 $transaction->allow_commit();
1066 $cmcontext = context_module::instance($data->coursemoduleid, MUST_EXIST);
1067 $coursecontext = $cmcontext->get_parent_context();
1069 $completioncache = cache::make('core', 'completion');
1070 if ($data->userid == $USER->id) {
1071 // Update module completion in user's cache.
1072 if (!($cachedata = $completioncache->get($data->userid . '_' . $cm->course))
1073 || $cachedata['cacherev'] != $this->course->cacherev) {
1074 $cachedata = array('cacherev' => $this->course->cacherev);
1076 $cachedata[$cm->id] = $data;
1077 $completioncache->set($data->userid . '_' . $cm->course, $cachedata);
1079 // reset modinfo for user (no need to call rebuild_course_cache())
1080 get_fast_modinfo($cm->course, 0, true);
1081 } else {
1082 // Remove another user's completion cache for this course.
1083 $completioncache->delete($data->userid . '_' . $cm->course);
1086 // Trigger an event for course module completion changed.
1087 $event = \core\event\course_module_completion_updated::create(array(
1088 'objectid' => $data->id,
1089 'context' => $cmcontext,
1090 'relateduserid' => $data->userid,
1091 'other' => array(
1092 'relateduserid' => $data->userid,
1093 'overrideby' => $data->overrideby,
1094 'completionstate' => $data->completionstate
1097 $event->add_record_snapshot('course_modules_completion', $data);
1098 $event->trigger();
1102 * Return whether or not the course has activities with completion enabled.
1104 * @return boolean true when there is at least one activity with completion enabled.
1106 public function has_activities() {
1107 $modinfo = get_fast_modinfo($this->course);
1108 foreach ($modinfo->get_cms() as $cm) {
1109 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1110 return true;
1113 return false;
1117 * Obtains a list of activities for which completion is enabled on the
1118 * course. The list is ordered by the section order of those activities.
1120 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1121 * empty array if none
1123 public function get_activities() {
1124 $modinfo = get_fast_modinfo($this->course);
1125 $result = array();
1126 foreach ($modinfo->get_cms() as $cm) {
1127 if ($cm->completion != COMPLETION_TRACKING_NONE && !$cm->deletioninprogress) {
1128 $result[$cm->id] = $cm;
1131 return $result;
1135 * Checks to see if the userid supplied has a tracked role in
1136 * this course
1138 * @param int $userid User id
1139 * @return bool
1141 public function is_tracked_user($userid) {
1142 return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1146 * Returns the number of users whose progress is tracked in this course.
1148 * Optionally supply a search's where clause, or a group id.
1150 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1151 * @param array $whereparams Where clause params
1152 * @param int $groupid Group id
1153 * @return int Number of tracked users
1155 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1156 global $DB;
1158 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1159 context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1160 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1161 if ($where) {
1162 $sql .= " WHERE $where";
1165 $params = array_merge($enrolledparams, $whereparams);
1166 return $DB->count_records_sql($sql, $params);
1170 * Return array of users whose progress is tracked in this course.
1172 * Optionally supply a search's where clause, group id, sorting, paging.
1174 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1175 * @param array $whereparams Where clause params (optional)
1176 * @param int $groupid Group ID to restrict to (optional)
1177 * @param string $sort Order by clause (optional)
1178 * @param int $limitfrom Result start (optional)
1179 * @param int $limitnum Result max size (optional)
1180 * @param context $extracontext If set, includes extra user information fields
1181 * as appropriate to display for current user in this context
1182 * @return array Array of user objects with standard user fields
1184 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1185 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1187 global $DB;
1189 list($enrolledsql, $params) = get_enrolled_sql(
1190 context_course::instance($this->course->id),
1191 'moodle/course:isincompletionreports', $groupid, true);
1193 $allusernames = get_all_user_name_fields(true, 'u');
1194 $sql = 'SELECT u.id, u.idnumber, ' . $allusernames;
1195 if ($extracontext) {
1196 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1198 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1200 if ($where) {
1201 $sql .= " AND $where";
1202 $params = array_merge($params, $whereparams);
1205 if ($sort) {
1206 $sql .= " ORDER BY $sort";
1209 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1213 * Obtains progress information across a course for all users on that course, or
1214 * for all users in a specific group. Intended for use when displaying progress.
1216 * This includes only users who, in course context, have one of the roles for
1217 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1219 * Users are included (in the first array) even if they do not have
1220 * completion progress for any course-module.
1222 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1223 * last name
1224 * @param string $where Where clause sql (optional)
1225 * @param array $where_params Where clause params (optional)
1226 * @param int $groupid Group ID or 0 (default)/false for all groups
1227 * @param int $pagesize Number of users to actually return (optional)
1228 * @param int $start User to start at if paging (optional)
1229 * @param context $extracontext If set, includes extra user information fields
1230 * as appropriate to display for current user in this context
1231 * @return stdClass with ->total and ->start (same as $start) and ->users;
1232 * an array of user objects (like mdl_user id, firstname, lastname)
1233 * containing an additional ->progress array of coursemoduleid => completionstate
1235 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1236 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1237 global $CFG, $DB;
1239 // Get list of applicable users
1240 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1241 $start, $pagesize, $extracontext);
1243 // Get progress information for these users in groups of 1, 000 (if needed)
1244 // to avoid making the SQL IN too long
1245 $results = array();
1246 $userids = array();
1247 foreach ($users as $user) {
1248 $userids[] = $user->id;
1249 $results[$user->id] = $user;
1250 $results[$user->id]->progress = array();
1253 for($i=0; $i<count($userids); $i+=1000) {
1254 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1256 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1257 array_splice($params, 0, 0, array($this->course->id));
1258 $rs = $DB->get_recordset_sql("
1259 SELECT
1260 cmc.*
1261 FROM
1262 {course_modules} cm
1263 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1264 WHERE
1265 cm.course=? AND cmc.userid $insql", $params);
1266 foreach ($rs as $progress) {
1267 $progress = (object)$progress;
1268 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1270 $rs->close();
1273 return $results;
1277 * Called by grade code to inform the completion system when a grade has
1278 * been changed. If the changed grade is used to determine completion for
1279 * the course-module, then the completion status will be updated.
1281 * @param stdClass|cm_info $cm Course-module for item that owns grade
1282 * @param grade_item $item Grade item
1283 * @param stdClass $grade
1284 * @param bool $deleted
1286 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1287 // Bail out now if completion is not enabled for course-module, it is enabled
1288 // but is set to manual, grade is not used to compute completion, or this
1289 // is a different numbered grade
1290 if (!$this->is_enabled($cm) ||
1291 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1292 is_null($cm->completiongradeitemnumber) ||
1293 $item->itemnumber != $cm->completiongradeitemnumber) {
1294 return;
1297 // What is the expected result based on this grade?
1298 if ($deleted) {
1299 // Grade being deleted, so only change could be to make it incomplete
1300 $possibleresult = COMPLETION_INCOMPLETE;
1301 } else {
1302 $possibleresult = self::internal_get_grade_state($item, $grade);
1305 // OK, let's update state based on this
1306 $this->update_state($cm, $possibleresult, $grade->userid);
1310 * Calculates the completion state that would result from a graded item
1311 * (where grade-based completion is turned on) based on the actual grade
1312 * and settings.
1314 * Internal function. Not private, so we can unit-test it.
1316 * @param grade_item $item an instance of grade_item
1317 * @param grade_grade $grade an instance of grade_grade
1318 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1320 public static function internal_get_grade_state($item, $grade) {
1321 // If no grade is supplied or the grade doesn't have an actual value, then
1322 // this is not complete.
1323 if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1324 return COMPLETION_INCOMPLETE;
1327 // Conditions to show pass/fail:
1328 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1329 // b) Grade is visible (neither hidden nor hidden-until)
1330 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1331 // Use final grade if set otherwise raw grade
1332 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1334 // We are displaying and tracking pass/fail
1335 if ($score >= $item->gradepass) {
1336 return COMPLETION_COMPLETE_PASS;
1337 } else {
1338 return COMPLETION_COMPLETE_FAIL;
1340 } else {
1341 // Not displaying pass/fail, so just if there is a grade
1342 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1343 // Grade exists, so maybe complete now
1344 return COMPLETION_COMPLETE;
1345 } else {
1346 // Grade does not exist, so maybe incomplete now
1347 return COMPLETION_INCOMPLETE;
1353 * Aggregate activity completion state
1355 * @param int $type Aggregation type (COMPLETION_* constant)
1356 * @param bool $old Old state
1357 * @param bool $new New state
1358 * @return bool
1360 public static function aggregate_completion_states($type, $old, $new) {
1361 if ($type == COMPLETION_AND) {
1362 return $old && $new;
1363 } else {
1364 return $old || $new;
1369 * This is to be used only for system errors (things that shouldn't happen)
1370 * and not user-level errors.
1372 * @global type $CFG
1373 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1374 * @throws moodle_exception Exception with the error string as debug info
1376 public function internal_systemerror($error) {
1377 global $CFG;
1378 throw new moodle_exception('err_system','completion',
1379 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1384 * Aggregate criteria status's as per configured aggregation method.
1386 * @param int $method COMPLETION_AGGREGATION_* constant.
1387 * @param bool $data Criteria completion status.
1388 * @param bool|null $state Aggregation state.
1390 function completion_cron_aggregate($method, $data, &$state) {
1391 if ($method == COMPLETION_AGGREGATION_ALL) {
1392 if ($data && $state !== false) {
1393 $state = true;
1394 } else {
1395 $state = false;
1397 } else if ($method == COMPLETION_AGGREGATION_ANY) {
1398 if ($data) {
1399 $state = true;
1400 } else if (!$data && $state === null) {
1401 $state = false;