Merge branch 'MDL-43230-master' of git://github.com/ryanwyllie/moodle
[moodle.git] / lib / completionlib.php
blobcba3ed9707a2322d4460bcc29aca97d3d1c1aabc
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Contains classes, functions and constants used during the tracking
19 * of activity completion for users.
21 * Completion top-level options (admin setting enablecompletion)
23 * @package core_completion
24 * @category completion
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * Include the required completion libraries
34 require_once $CFG->dirroot.'/completion/completion_aggregation.php';
35 require_once $CFG->dirroot.'/completion/criteria/completion_criteria.php';
36 require_once $CFG->dirroot.'/completion/completion_completion.php';
37 require_once $CFG->dirroot.'/completion/completion_criteria_completion.php';
40 /**
41 * The completion system is enabled in this site/course
43 define('COMPLETION_ENABLED', 1);
44 /**
45 * The completion system is not enabled in this site/course
47 define('COMPLETION_DISABLED', 0);
49 /**
50 * Completion tracking is disabled for this activity
51 * This is a completion tracking option per-activity (course_modules/completion)
53 define('COMPLETION_TRACKING_NONE', 0);
55 /**
56 * Manual completion tracking (user ticks box) is enabled for this activity
57 * This is a completion tracking option per-activity (course_modules/completion)
59 define('COMPLETION_TRACKING_MANUAL', 1);
60 /**
61 * Automatic completion tracking (system ticks box) is enabled for this activity
62 * This is a completion tracking option per-activity (course_modules/completion)
64 define('COMPLETION_TRACKING_AUTOMATIC', 2);
66 /**
67 * The user has not completed this activity.
68 * This is a completion state value (course_modules_completion/completionstate)
70 define('COMPLETION_INCOMPLETE', 0);
71 /**
72 * The user has completed this activity. It is not specified whether they have
73 * passed or failed it.
74 * This is a completion state value (course_modules_completion/completionstate)
76 define('COMPLETION_COMPLETE', 1);
77 /**
78 * The user has completed this activity with a grade above the pass mark.
79 * This is a completion state value (course_modules_completion/completionstate)
81 define('COMPLETION_COMPLETE_PASS', 2);
82 /**
83 * The user has completed this activity but their grade is less than the pass mark
84 * This is a completion state value (course_modules_completion/completionstate)
86 define('COMPLETION_COMPLETE_FAIL', 3);
88 /**
89 * The effect of this change to completion status is unknown.
90 * A completion effect changes (used only in update_state)
92 define('COMPLETION_UNKNOWN', -1);
93 /**
94 * The user's grade has changed, so their new state might be
95 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
96 * A completion effect changes (used only in update_state)
98 define('COMPLETION_GRADECHANGE', -2);
101 * User must view this activity.
102 * Whether view is required to create an activity (course_modules/completionview)
104 define('COMPLETION_VIEW_REQUIRED', 1);
106 * User does not need to view this activity
107 * Whether view is required to create an activity (course_modules/completionview)
109 define('COMPLETION_VIEW_NOT_REQUIRED', 0);
112 * User has viewed this activity.
113 * Completion viewed state (course_modules_completion/viewed)
115 define('COMPLETION_VIEWED', 1);
117 * User has not viewed this activity.
118 * Completion viewed state (course_modules_completion/viewed)
120 define('COMPLETION_NOT_VIEWED', 0);
123 * Completion details should be ORed together and you should return false if
124 * none apply.
126 define('COMPLETION_OR', false);
128 * Completion details should be ANDed together and you should return true if
129 * none apply
131 define('COMPLETION_AND', true);
134 * Course completion criteria aggregation method.
136 define('COMPLETION_AGGREGATION_ALL', 1);
138 * Course completion criteria aggregation method.
140 define('COMPLETION_AGGREGATION_ANY', 2);
144 * Utility function for checking if the logged in user can view
145 * another's completion data for a particular course
147 * @access public
148 * @param int $userid Completion data's owner
149 * @param mixed $course Course object or Course ID (optional)
150 * @return boolean
152 function completion_can_view_data($userid, $course = null) {
153 global $USER;
155 if (!isloggedin()) {
156 return false;
159 if (!is_object($course)) {
160 $cid = $course;
161 $course = new stdClass();
162 $course->id = $cid;
165 // Check if this is the site course
166 if ($course->id == SITEID) {
167 $course = null;
170 // Check if completion is enabled
171 if ($course) {
172 $cinfo = new completion_info($course);
173 if (!$cinfo->is_enabled()) {
174 return false;
176 } else {
177 if (!completion_info::is_enabled_for_site()) {
178 return false;
182 // Is own user's data?
183 if ($USER->id == $userid) {
184 return true;
187 // Check capabilities
188 $personalcontext = context_user::instance($userid);
190 if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
191 return true;
192 } elseif (has_capability('report/completion:view', $personalcontext)) {
193 return true;
196 if ($course->id) {
197 $coursecontext = context_course::instance($course->id);
198 } else {
199 $coursecontext = context_system::instance();
202 if (has_capability('report/completion:view', $coursecontext)) {
203 return true;
206 return false;
211 * Class represents completion information for a course.
213 * Does not contain any data, so you can safely construct it multiple times
214 * without causing any problems.
216 * @package core
217 * @category completion
218 * @copyright 2008 Sam Marshall
219 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
221 class completion_info {
223 /* @var stdClass Course object passed during construction */
224 private $course;
226 /* @var int Course id */
227 public $course_id;
229 /* @var array Completion criteria {@link completion_info::get_criteria()} */
230 private $criteria;
233 * Return array of aggregation methods
234 * @return array
236 public static function get_aggregation_methods() {
237 return array(
238 COMPLETION_AGGREGATION_ALL => get_string('all'),
239 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
244 * Constructs with course details.
246 * When instantiating a new completion info object you must provide a course
247 * object with at least id, and enablecompletion properties. Property
248 * cacherev is needed if you check completion of the current user since
249 * it is used for cache validation.
251 * @param stdClass $course Moodle course object.
253 public function __construct($course) {
254 $this->course = $course;
255 $this->course_id = $course->id;
259 * Determines whether completion is enabled across entire site.
261 * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
262 * COMPLETION_DISABLED (false) if it's complete
264 public static function is_enabled_for_site() {
265 global $CFG;
266 return !empty($CFG->enablecompletion);
270 * Checks whether completion is enabled in a particular course and possibly
271 * activity.
273 * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
274 * completion enable state.
275 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
276 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
277 * for a course-module.
279 public function is_enabled($cm = null) {
280 global $CFG, $DB;
282 // First check global completion
283 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
284 return COMPLETION_DISABLED;
287 // Load data if we do not have enough
288 if (!isset($this->course->enablecompletion)) {
289 $this->course = get_course($this->course_id);
292 // Check course completion
293 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
294 return COMPLETION_DISABLED;
297 // If there was no $cm and we got this far, then it's enabled
298 if (!$cm) {
299 return COMPLETION_ENABLED;
302 // Return course-module completion value
303 return $cm->completion;
307 * Displays the 'Your progress' help icon, if completion tracking is enabled.
308 * Just prints the result of display_help_icon().
310 * @deprecated since Moodle 2.0 - Use display_help_icon instead.
312 public function print_help_icon() {
313 print $this->display_help_icon();
317 * Returns the 'Your progress' help icon, if completion tracking is enabled.
319 * @return string HTML code for help icon, or blank if not needed
321 public function display_help_icon() {
322 global $PAGE, $OUTPUT;
323 $result = '';
324 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
325 $result .= html_writer::tag('div', get_string('yourprogress','completion') .
326 $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
327 'class' => 'completionprogress'));
329 return $result;
333 * Get a course completion for a user
335 * @param int $user_id User id
336 * @param int $criteriatype Specific criteria type to return
337 * @return bool|completion_criteria_completion returns false on fail
339 public function get_completion($user_id, $criteriatype) {
340 $completions = $this->get_completions($user_id, $criteriatype);
342 if (empty($completions)) {
343 return false;
344 } elseif (count($completions) > 1) {
345 print_error('multipleselfcompletioncriteria', 'completion');
348 return $completions[0];
352 * Get all course criteria's completion objects for a user
354 * @param int $user_id User id
355 * @param int $criteriatype Specific criteria type to return (optional)
356 * @return array
358 public function get_completions($user_id, $criteriatype = null) {
359 $criterion = $this->get_criteria($criteriatype);
361 $completions = array();
363 foreach ($criterion as $criteria) {
364 $params = array(
365 'course' => $this->course_id,
366 'userid' => $user_id,
367 'criteriaid' => $criteria->id
370 $completion = new completion_criteria_completion($params);
371 $completion->attach_criteria($criteria);
373 $completions[] = $completion;
376 return $completions;
380 * Get completion object for a user and a criteria
382 * @param int $user_id User id
383 * @param completion_criteria $criteria Criteria object
384 * @return completion_criteria_completion
386 public function get_user_completion($user_id, $criteria) {
387 $params = array(
388 'course' => $this->course_id,
389 'userid' => $user_id,
390 'criteriaid' => $criteria->id,
393 $completion = new completion_criteria_completion($params);
394 return $completion;
398 * Check if course has completion criteria set
400 * @return bool Returns true if there are criteria
402 public function has_criteria() {
403 $criteria = $this->get_criteria();
405 return (bool) count($criteria);
409 * Get course completion criteria
411 * @param int $criteriatype Specific criteria type to return (optional)
413 public function get_criteria($criteriatype = null) {
415 // Fill cache if empty
416 if (!is_array($this->criteria)) {
417 global $DB;
419 $params = array(
420 'course' => $this->course->id
423 // Load criteria from database
424 $records = (array)$DB->get_records('course_completion_criteria', $params);
426 // Build array of criteria objects
427 $this->criteria = array();
428 foreach ($records as $record) {
429 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
433 // If after all criteria
434 if ($criteriatype === null) {
435 return $this->criteria;
438 // If we are only after a specific criteria type
439 $criteria = array();
440 foreach ($this->criteria as $criterion) {
442 if ($criterion->criteriatype != $criteriatype) {
443 continue;
446 $criteria[$criterion->id] = $criterion;
449 return $criteria;
453 * Get aggregation method
455 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
456 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
458 public function get_aggregation_method($criteriatype = null) {
459 $params = array(
460 'course' => $this->course_id,
461 'criteriatype' => $criteriatype
464 $aggregation = new completion_aggregation($params);
466 if (!$aggregation->id) {
467 $aggregation->method = COMPLETION_AGGREGATION_ALL;
470 return $aggregation->method;
474 * @deprecated since Moodle 2.8 MDL-46290.
476 public function get_incomplete_criteria() {
477 throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
481 * Clear old course completion criteria
483 public function clear_criteria() {
484 global $DB;
485 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id));
486 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
488 $this->delete_course_completion_data();
492 * Has the supplied user completed this course
494 * @param int $user_id User's id
495 * @return boolean
497 public function is_course_complete($user_id) {
498 $params = array(
499 'userid' => $user_id,
500 'course' => $this->course_id
503 $ccompletion = new completion_completion($params);
504 return $ccompletion->is_complete();
508 * Updates (if necessary) the completion state of activity $cm for the given
509 * user.
511 * For manual completion, this function is called when completion is toggled
512 * with $possibleresult set to the target state.
514 * For automatic completion, this function should be called every time a module
515 * does something which might influence a user's completion state. For example,
516 * if a forum provides options for marking itself 'completed' once a user makes
517 * N posts, this function should be called every time a user makes a new post.
518 * [After the post has been saved to the database]. When calling, you do not
519 * need to pass in the new completion state. Instead this function carries out
520 * completion calculation by checking grades and viewed state itself, and
521 * calling the involved module via modulename_get_completion_state() to check
522 * module-specific conditions.
524 * @param stdClass|cm_info $cm Course-module
525 * @param int $possibleresult Expected completion result. If the event that
526 * has just occurred (e.g. add post) can only result in making the activity
527 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
528 * has just occurred (e.g. delete post) can only result in making the activity
529 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
530 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
531 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
532 * processing early if the user's completion state already matches the expected
533 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
534 * must be used; these directly set the specified state.
535 * @param int $userid User ID to be updated. Default 0 = current user
536 * @return void
538 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
539 global $USER;
541 // Do nothing if completion is not enabled for that activity
542 if (!$this->is_enabled($cm)) {
543 return;
546 // Get current value of completion state and do nothing if it's same as
547 // the possible result of this change. If the change is to COMPLETE and the
548 // current value is one of the COMPLETE_xx subtypes, ignore that as well
549 $current = $this->get_data($cm, false, $userid);
550 if ($possibleresult == $current->completionstate ||
551 ($possibleresult == COMPLETION_COMPLETE &&
552 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
553 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
554 return;
557 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
558 // For manual tracking we set the result directly
559 switch($possibleresult) {
560 case COMPLETION_COMPLETE:
561 case COMPLETION_INCOMPLETE:
562 $newstate = $possibleresult;
563 break;
564 default:
565 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
568 } else {
569 // Automatic tracking; get new state
570 $newstate = $this->internal_get_state($cm, $userid, $current);
573 // If changed, update
574 if ($newstate != $current->completionstate) {
575 $current->completionstate = $newstate;
576 $current->timemodified = time();
577 $this->internal_set_data($cm, $current);
582 * Calculates the completion state for an activity and user.
584 * Internal function. Not private, so we can unit-test it.
586 * @param stdClass|cm_info $cm Activity
587 * @param int $userid ID of user
588 * @param stdClass $current Previous completion information from database
589 * @return mixed
591 public function internal_get_state($cm, $userid, $current) {
592 global $USER, $DB, $CFG;
594 // Get user ID
595 if (!$userid) {
596 $userid = $USER->id;
599 // Check viewed
600 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
601 $current->viewed == COMPLETION_NOT_VIEWED) {
603 return COMPLETION_INCOMPLETE;
606 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
607 if (!isset($cm->modname)) {
608 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
611 $newstate = COMPLETION_COMPLETE;
613 // Check grade
614 if (!is_null($cm->completiongradeitemnumber)) {
615 require_once($CFG->libdir.'/gradelib.php');
616 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
617 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
618 'itemnumber'=>$cm->completiongradeitemnumber));
619 if ($item) {
620 // Fetch 'grades' (will be one or none)
621 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
622 if (empty($grades)) {
623 // No grade for user
624 return COMPLETION_INCOMPLETE;
626 if (count($grades) > 1) {
627 $this->internal_systemerror("Unexpected result: multiple grades for
628 item '{$item->id}', user '{$userid}'");
630 $newstate = self::internal_get_grade_state($item, reset($grades));
631 if ($newstate == COMPLETION_INCOMPLETE) {
632 return COMPLETION_INCOMPLETE;
635 } else {
636 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
637 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
641 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
642 $function = $cm->modname.'_get_completion_state';
643 if (!function_exists($function)) {
644 $this->internal_systemerror("Module {$cm->modname} claims to support
645 FEATURE_COMPLETION_HAS_RULES but does not have required
646 {$cm->modname}_get_completion_state function");
648 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
649 return COMPLETION_INCOMPLETE;
653 return $newstate;
658 * Marks a module as viewed.
660 * Should be called whenever a module is 'viewed' (it is up to the module how to
661 * determine that). Has no effect if viewing is not set as a completion condition.
663 * Note that this function must be called before you print the page header because
664 * it is possible that the navigation block may depend on it. If you call it after
665 * printing the header, it shows a developer debug warning.
667 * @param stdClass|cm_info $cm Activity
668 * @param int $userid User ID or 0 (default) for current user
669 * @return void
671 public function set_module_viewed($cm, $userid=0) {
672 global $PAGE;
673 if ($PAGE->headerprinted) {
674 debugging('set_module_viewed must be called before header is printed',
675 DEBUG_DEVELOPER);
678 // Don't do anything if view condition is not turned on
679 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
680 return;
683 // Get current completion state
684 $data = $this->get_data($cm, false, $userid);
686 // If we already viewed it, don't do anything
687 if ($data->viewed == COMPLETION_VIEWED) {
688 return;
691 // OK, change state, save it, and update completion
692 $data->viewed = COMPLETION_VIEWED;
693 $this->internal_set_data($cm, $data);
694 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
698 * Determines how much completion data exists for an activity. This is used when
699 * deciding whether completion information should be 'locked' in the module
700 * editing form.
702 * @param cm_info $cm Activity
703 * @return int The number of users who have completion data stored for this
704 * activity, 0 if none
706 public function count_user_data($cm) {
707 global $DB;
709 return $DB->get_field_sql("
710 SELECT
711 COUNT(1)
712 FROM
713 {course_modules_completion}
714 WHERE
715 coursemoduleid=? AND completionstate<>0", array($cm->id));
719 * Determines how much course completion data exists for a course. This is used when
720 * deciding whether completion information should be 'locked' in the completion
721 * settings form and activity completion settings.
723 * @param int $user_id Optionally only get course completion data for a single user
724 * @return int The number of users who have completion data stored for this
725 * course, 0 if none
727 public function count_course_user_data($user_id = null) {
728 global $DB;
730 $sql = '
731 SELECT
732 COUNT(1)
733 FROM
734 {course_completion_crit_compl}
735 WHERE
736 course = ?
739 $params = array($this->course_id);
741 // Limit data to a single user if an ID is supplied
742 if ($user_id) {
743 $sql .= ' AND userid = ?';
744 $params[] = $user_id;
747 return $DB->get_field_sql($sql, $params);
751 * Check if this course's completion criteria should be locked
753 * @return boolean
755 public function is_course_locked() {
756 return (bool) $this->count_course_user_data();
760 * Deletes all course completion completion data.
762 * Intended to be used when unlocking completion criteria settings.
764 public function delete_course_completion_data() {
765 global $DB;
767 $DB->delete_records('course_completions', array('course' => $this->course_id));
768 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
770 // Difficult to find affected users, just purge all completion cache.
771 cache::make('core', 'completion')->purge();
775 * Deletes all activity and course completion data for an entire course
776 * (the below delete_all_state function does this for a single activity).
778 * Used by course reset page.
780 public function delete_all_completion_data() {
781 global $DB;
783 // Delete from database.
784 $DB->delete_records_select('course_modules_completion',
785 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
786 array($this->course_id));
788 // Wipe course completion data too.
789 $this->delete_course_completion_data();
793 * Deletes completion state related to an activity for all users.
795 * Intended for use only when the activity itself is deleted.
797 * @param stdClass|cm_info $cm Activity
799 public function delete_all_state($cm) {
800 global $DB;
802 // Delete from database
803 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
805 // Check if there is an associated course completion criteria
806 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
807 $acriteria = false;
808 foreach ($criteria as $criterion) {
809 if ($criterion->moduleinstance == $cm->id) {
810 $acriteria = $criterion;
811 break;
815 if ($acriteria) {
816 // Delete all criteria completions relating to this activity
817 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
818 $DB->delete_records('course_completions', array('course' => $this->course_id));
821 // Difficult to find affected users, just purge all completion cache.
822 cache::make('core', 'completion')->purge();
826 * Recalculates completion state related to an activity for all users.
828 * Intended for use if completion conditions change. (This should be avoided
829 * as it may cause some things to become incomplete when they were previously
830 * complete, with the effect - for example - of hiding a later activity that
831 * was previously available.)
833 * Resetting state of manual tickbox has same result as deleting state for
834 * it.
836 * @param stcClass|cm_info $cm Activity
838 public function reset_all_state($cm) {
839 global $DB;
841 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
842 $this->delete_all_state($cm);
843 return;
845 // Get current list of users with completion state
846 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
847 $keepusers = array();
848 foreach ($rs as $rec) {
849 $keepusers[] = $rec->userid;
851 $rs->close();
853 // Delete all existing state.
854 $this->delete_all_state($cm);
856 // Merge this with list of planned users (according to roles)
857 $trackedusers = $this->get_tracked_users();
858 foreach ($trackedusers as $trackeduser) {
859 $keepusers[] = $trackeduser->id;
861 $keepusers = array_unique($keepusers);
863 // Recalculate state for each kept user
864 foreach ($keepusers as $keepuser) {
865 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
870 * Obtains completion data for a particular activity and user (from the
871 * completion cache if available, or by SQL query)
873 * @param stcClass|cm_info $cm Activity; only required field is ->id
874 * @param bool $wholecourse If true (default false) then, when necessary to
875 * fill the cache, retrieves information from the entire course not just for
876 * this one activity
877 * @param int $userid User ID or 0 (default) for current user
878 * @param array $modinfo Supply the value here - this is used for unit
879 * testing and so that it can be called recursively from within
880 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
881 * Otherwise the method calls get_fast_modinfo itself.
882 * @return object Completion data (record from course_modules_completion)
884 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
885 global $USER, $CFG, $DB;
886 $completioncache = cache::make('core', 'completion');
888 // Get user ID
889 if (!$userid) {
890 $userid = $USER->id;
893 // See if requested data is present in cache (use cache for current user only).
894 $usecache = $userid == $USER->id;
895 $cacheddata = array();
896 if ($usecache) {
897 $key = $userid . '_' . $this->course->id;
898 if (!isset($this->course->cacherev)) {
899 $this->course = get_course($this->course_id);
901 if ($cacheddata = $completioncache->get($key)) {
902 if ($cacheddata['cacherev'] != $this->course->cacherev) {
903 // Course structure has been changed since the last caching, forget the cache.
904 $cacheddata = array();
905 } else if (isset($cacheddata[$cm->id])) {
906 return (object)$cacheddata[$cm->id];
911 // Not there, get via SQL
912 if ($usecache && $wholecourse) {
913 // Get whole course data for cache
914 $alldatabycmc = $DB->get_records_sql("
915 SELECT
916 cmc.*
917 FROM
918 {course_modules} cm
919 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
920 WHERE
921 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
923 // Reindex by cm id
924 $alldata = array();
925 foreach ($alldatabycmc as $data) {
926 $alldata[$data->coursemoduleid] = (array)$data;
929 // Get the module info and build up condition info for each one
930 if (empty($modinfo)) {
931 $modinfo = get_fast_modinfo($this->course, $userid);
933 foreach ($modinfo->cms as $othercm) {
934 if (isset($alldata[$othercm->id])) {
935 $data = $alldata[$othercm->id];
936 } else {
937 // Row not present counts as 'not complete'
938 $data = array();
939 $data['id'] = 0;
940 $data['coursemoduleid'] = $othercm->id;
941 $data['userid'] = $userid;
942 $data['completionstate'] = 0;
943 $data['viewed'] = 0;
944 $data['timemodified'] = 0;
946 $cacheddata[$othercm->id] = $data;
949 if (!isset($cacheddata[$cm->id])) {
950 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
953 } else {
954 // Get single record
955 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
956 if ($data) {
957 $data = (array)$data;
958 } else {
959 // Row not present counts as 'not complete'
960 $data = array();
961 $data['id'] = 0;
962 $data['coursemoduleid'] = $cm->id;
963 $data['userid'] = $userid;
964 $data['completionstate'] = 0;
965 $data['viewed'] = 0;
966 $data['timemodified'] = 0;
969 // Put in cache
970 $cacheddata[$cm->id] = $data;
973 if ($usecache) {
974 $cacheddata['cacherev'] = $this->course->cacherev;
975 $completioncache->set($key, $cacheddata);
977 return (object)$cacheddata[$cm->id];
981 * Updates completion data for a particular coursemodule and user (user is
982 * determined from $data).
984 * (Internal function. Not private, so we can unit-test it.)
986 * @param stdClass|cm_info $cm Activity
987 * @param stdClass $data Data about completion for that user
989 public function internal_set_data($cm, $data) {
990 global $USER, $DB;
992 $transaction = $DB->start_delegated_transaction();
993 if (!$data->id) {
994 // Check there isn't really a row
995 $data->id = $DB->get_field('course_modules_completion', 'id',
996 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
998 if (!$data->id) {
999 // Didn't exist before, needs creating
1000 $data->id = $DB->insert_record('course_modules_completion', $data);
1001 } else {
1002 // Has real (nonzero) id meaning that a database row exists, update
1003 $DB->update_record('course_modules_completion', $data);
1005 $transaction->allow_commit();
1007 $cmcontext = context_module::instance($data->coursemoduleid, MUST_EXIST);
1008 $coursecontext = $cmcontext->get_parent_context();
1010 $completioncache = cache::make('core', 'completion');
1011 if ($data->userid == $USER->id) {
1012 // Update module completion in user's cache.
1013 if (!($cachedata = $completioncache->get($data->userid . '_' . $cm->course))
1014 || $cachedata['cacherev'] != $this->course->cacherev) {
1015 $cachedata = array('cacherev' => $this->course->cacherev);
1017 $cachedata[$cm->id] = $data;
1018 $completioncache->set($data->userid . '_' . $cm->course, $cachedata);
1020 // reset modinfo for user (no need to call rebuild_course_cache())
1021 get_fast_modinfo($cm->course, 0, true);
1022 } else {
1023 // Remove another user's completion cache for this course.
1024 $completioncache->delete($data->userid . '_' . $cm->course);
1027 // Trigger an event for course module completion changed.
1028 $event = \core\event\course_module_completion_updated::create(array(
1029 'objectid' => $data->id,
1030 'context' => $cmcontext,
1031 'relateduserid' => $data->userid,
1032 'other' => array(
1033 'relateduserid' => $data->userid
1036 $event->add_record_snapshot('course_modules_completion', $data);
1037 $event->trigger();
1041 * Return whether or not the course has activities with completion enabled.
1043 * @return boolean true when there is at least one activity with completion enabled.
1045 public function has_activities() {
1046 $modinfo = get_fast_modinfo($this->course);
1047 foreach ($modinfo->get_cms() as $cm) {
1048 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1049 return true;
1052 return false;
1056 * Obtains a list of activities for which completion is enabled on the
1057 * course. The list is ordered by the section order of those activities.
1059 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1060 * empty array if none
1062 public function get_activities() {
1063 $modinfo = get_fast_modinfo($this->course);
1064 $result = array();
1065 foreach ($modinfo->get_cms() as $cm) {
1066 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1067 $result[$cm->id] = $cm;
1070 return $result;
1074 * Checks to see if the userid supplied has a tracked role in
1075 * this course
1077 * @param int $userid User id
1078 * @return bool
1080 public function is_tracked_user($userid) {
1081 return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1085 * Returns the number of users whose progress is tracked in this course.
1087 * Optionally supply a search's where clause, or a group id.
1089 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1090 * @param array $whereparams Where clause params
1091 * @param int $groupid Group id
1092 * @return int Number of tracked users
1094 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1095 global $DB;
1097 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1098 context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1099 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1100 if ($where) {
1101 $sql .= " WHERE $where";
1104 $params = array_merge($enrolledparams, $whereparams);
1105 return $DB->count_records_sql($sql, $params);
1109 * Return array of users whose progress is tracked in this course.
1111 * Optionally supply a search's where clause, group id, sorting, paging.
1113 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1114 * @param array $whereparams Where clause params (optional)
1115 * @param int $groupid Group ID to restrict to (optional)
1116 * @param string $sort Order by clause (optional)
1117 * @param int $limitfrom Result start (optional)
1118 * @param int $limitnum Result max size (optional)
1119 * @param context $extracontext If set, includes extra user information fields
1120 * as appropriate to display for current user in this context
1121 * @return array Array of user objects with standard user fields
1123 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1124 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1126 global $DB;
1128 list($enrolledsql, $params) = get_enrolled_sql(
1129 context_course::instance($this->course->id),
1130 'moodle/course:isincompletionreports', $groupid, true);
1132 $allusernames = get_all_user_name_fields(true, 'u');
1133 $sql = 'SELECT u.id, u.idnumber, ' . $allusernames;
1134 if ($extracontext) {
1135 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1137 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1139 if ($where) {
1140 $sql .= " AND $where";
1141 $params = array_merge($params, $whereparams);
1144 if ($sort) {
1145 $sql .= " ORDER BY $sort";
1148 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1152 * Obtains progress information across a course for all users on that course, or
1153 * for all users in a specific group. Intended for use when displaying progress.
1155 * This includes only users who, in course context, have one of the roles for
1156 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1158 * Users are included (in the first array) even if they do not have
1159 * completion progress for any course-module.
1161 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1162 * last name
1163 * @param string $where Where clause sql (optional)
1164 * @param array $where_params Where clause params (optional)
1165 * @param int $groupid Group ID or 0 (default)/false for all groups
1166 * @param int $pagesize Number of users to actually return (optional)
1167 * @param int $start User to start at if paging (optional)
1168 * @param context $extracontext If set, includes extra user information fields
1169 * as appropriate to display for current user in this context
1170 * @return stdClass with ->total and ->start (same as $start) and ->users;
1171 * an array of user objects (like mdl_user id, firstname, lastname)
1172 * containing an additional ->progress array of coursemoduleid => completionstate
1174 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1175 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1176 global $CFG, $DB;
1178 // Get list of applicable users
1179 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1180 $start, $pagesize, $extracontext);
1182 // Get progress information for these users in groups of 1, 000 (if needed)
1183 // to avoid making the SQL IN too long
1184 $results = array();
1185 $userids = array();
1186 foreach ($users as $user) {
1187 $userids[] = $user->id;
1188 $results[$user->id] = $user;
1189 $results[$user->id]->progress = array();
1192 for($i=0; $i<count($userids); $i+=1000) {
1193 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1195 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1196 array_splice($params, 0, 0, array($this->course->id));
1197 $rs = $DB->get_recordset_sql("
1198 SELECT
1199 cmc.*
1200 FROM
1201 {course_modules} cm
1202 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1203 WHERE
1204 cm.course=? AND cmc.userid $insql", $params);
1205 foreach ($rs as $progress) {
1206 $progress = (object)$progress;
1207 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1209 $rs->close();
1212 return $results;
1216 * Called by grade code to inform the completion system when a grade has
1217 * been changed. If the changed grade is used to determine completion for
1218 * the course-module, then the completion status will be updated.
1220 * @param stdClass|cm_info $cm Course-module for item that owns grade
1221 * @param grade_item $item Grade item
1222 * @param stdClass $grade
1223 * @param bool $deleted
1225 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1226 // Bail out now if completion is not enabled for course-module, it is enabled
1227 // but is set to manual, grade is not used to compute completion, or this
1228 // is a different numbered grade
1229 if (!$this->is_enabled($cm) ||
1230 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1231 is_null($cm->completiongradeitemnumber) ||
1232 $item->itemnumber != $cm->completiongradeitemnumber) {
1233 return;
1236 // What is the expected result based on this grade?
1237 if ($deleted) {
1238 // Grade being deleted, so only change could be to make it incomplete
1239 $possibleresult = COMPLETION_INCOMPLETE;
1240 } else {
1241 $possibleresult = self::internal_get_grade_state($item, $grade);
1244 // OK, let's update state based on this
1245 $this->update_state($cm, $possibleresult, $grade->userid);
1249 * Calculates the completion state that would result from a graded item
1250 * (where grade-based completion is turned on) based on the actual grade
1251 * and settings.
1253 * Internal function. Not private, so we can unit-test it.
1255 * @param grade_item $item an instance of grade_item
1256 * @param grade_grade $grade an instance of grade_grade
1257 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1259 public static function internal_get_grade_state($item, $grade) {
1260 // If no grade is supplied or the grade doesn't have an actual value, then
1261 // this is not complete.
1262 if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1263 return COMPLETION_INCOMPLETE;
1266 // Conditions to show pass/fail:
1267 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1268 // b) Grade is visible (neither hidden nor hidden-until)
1269 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1270 // Use final grade if set otherwise raw grade
1271 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1273 // We are displaying and tracking pass/fail
1274 if ($score >= $item->gradepass) {
1275 return COMPLETION_COMPLETE_PASS;
1276 } else {
1277 return COMPLETION_COMPLETE_FAIL;
1279 } else {
1280 // Not displaying pass/fail, so just if there is a grade
1281 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1282 // Grade exists, so maybe complete now
1283 return COMPLETION_COMPLETE;
1284 } else {
1285 // Grade does not exist, so maybe incomplete now
1286 return COMPLETION_INCOMPLETE;
1292 * Aggregate activity completion state
1294 * @param int $type Aggregation type (COMPLETION_* constant)
1295 * @param bool $old Old state
1296 * @param bool $new New state
1297 * @return bool
1299 public static function aggregate_completion_states($type, $old, $new) {
1300 if ($type == COMPLETION_AND) {
1301 return $old && $new;
1302 } else {
1303 return $old || $new;
1308 * This is to be used only for system errors (things that shouldn't happen)
1309 * and not user-level errors.
1311 * @global type $CFG
1312 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1313 * @throws moodle_exception Exception with the error string as debug info
1315 public function internal_systemerror($error) {
1316 global $CFG;
1317 throw new moodle_exception('err_system','completion',
1318 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);