2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Contains classes, functions and constants used during the tracking
19 * of activity completion for users.
21 * Completion top-level options (admin setting enablecompletion)
23 * @package core_completion
24 * @category completion
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') ||
die();
32 * Include the required completion libraries
34 require_once $CFG->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';
41 * The completion system is enabled in this site/course
43 define('COMPLETION_ENABLED', 1);
45 * The completion system is not enabled in this site/course
47 define('COMPLETION_DISABLED', 0);
50 * Completion tracking is disabled for this activity
51 * This is a completion tracking option per-activity (course_modules/completion)
53 define('COMPLETION_TRACKING_NONE', 0);
56 * Manual completion tracking (user ticks box) is enabled for this activity
57 * This is a completion tracking option per-activity (course_modules/completion)
59 define('COMPLETION_TRACKING_MANUAL', 1);
61 * Automatic completion tracking (system ticks box) is enabled for this activity
62 * This is a completion tracking option per-activity (course_modules/completion)
64 define('COMPLETION_TRACKING_AUTOMATIC', 2);
67 * The user has not completed this activity.
68 * This is a completion state value (course_modules_completion/completionstate)
70 define('COMPLETION_INCOMPLETE', 0);
72 * The user has completed this activity. It is not specified whether they have
73 * passed or failed it.
74 * This is a completion state value (course_modules_completion/completionstate)
76 define('COMPLETION_COMPLETE', 1);
78 * The user has completed this activity with a grade above the pass mark.
79 * This is a completion state value (course_modules_completion/completionstate)
81 define('COMPLETION_COMPLETE_PASS', 2);
83 * The user has completed this activity but their grade is less than the pass mark
84 * This is a completion state value (course_modules_completion/completionstate)
86 define('COMPLETION_COMPLETE_FAIL', 3);
89 * The effect of this change to completion status is unknown.
90 * A completion effect changes (used only in update_state)
92 define('COMPLETION_UNKNOWN', -1);
94 * The user's grade has changed, so their new state might be
95 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
96 * A completion effect changes (used only in update_state)
98 define('COMPLETION_GRADECHANGE', -2);
101 * User must view this activity.
102 * Whether view is required to create an activity (course_modules/completionview)
104 define('COMPLETION_VIEW_REQUIRED', 1);
106 * User does not need to view this activity
107 * Whether view is required to create an activity (course_modules/completionview)
109 define('COMPLETION_VIEW_NOT_REQUIRED', 0);
112 * User has viewed this activity.
113 * Completion viewed state (course_modules_completion/viewed)
115 define('COMPLETION_VIEWED', 1);
117 * User has not viewed this activity.
118 * Completion viewed state (course_modules_completion/viewed)
120 define('COMPLETION_NOT_VIEWED', 0);
123 * Completion details should be ORed together and you should return false if
126 define('COMPLETION_OR', false);
128 * Completion details should be ANDed together and you should return true if
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
148 * @param int $userid Completion data's owner
149 * @param mixed $course Course object or Course ID (optional)
152 function completion_can_view_data($userid, $course = null) {
159 if (!is_object($course)) {
161 $course = new object();
165 // Check if this is the site course
166 if ($course->id
== SITEID
) {
170 // Check if completion is enabled
172 $cinfo = new completion_info($course);
173 if (!$cinfo->is_enabled()) {
177 if (!completion_info
::is_enabled_for_site()) {
182 // Is own user's data?
183 if ($USER->id
== $userid) {
187 // Check capabilities
188 $personalcontext = context_user
::instance($userid);
190 if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
192 } elseif (has_capability('report/completion:view', $personalcontext)) {
197 $coursecontext = context_course
::instance($course->id
);
199 $coursecontext = context_system
::instance();
202 if (has_capability('report/completion:view', $coursecontext)) {
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.
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 */
226 /* @var int Course id */
229 /* @var array Completion criteria {@link completion_info::get_criteria()} */
233 * Return array of aggregation methods
236 public static function get_aggregation_methods() {
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() {
266 return !empty($CFG->enablecompletion
);
270 * Checks whether completion is enabled in a particular course and possibly
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) {
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
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;
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'));
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)) {
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)
358 public function get_completions($user_id, $criteriatype = null) {
359 $criterion = $this->get_criteria($criteriatype);
361 $completions = array();
363 foreach ($criterion as $criteria) {
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;
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) {
388 'course' => $this->course_id
,
389 'userid' => $user_id,
390 'criteriaid' => $criteria->id
,
393 $completion = new completion_criteria_completion($params);
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
)) {
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
440 foreach ($this->criteria
as $criterion) {
442 if ($criterion->criteriatype
!= $criteriatype) {
446 $criteria[$criterion->id
] = $criterion;
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) {
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 * Get incomplete course completion criteria
476 * @deprecated since Moodle 2.8 MDL-46290.
477 * @todo MDL-46294 This will be deleted in Moodle 3.0.
480 public function get_incomplete_criteria() {
481 debugging('completion_info->get_incomplete_criteria() is deprecated.', DEBUG_DEVELOPER
);
482 $incomplete = array();
484 foreach ($this->get_criteria() as $criteria) {
485 if (!$criteria->is_complete()) {
486 $incomplete[] = $criteria;
494 * Clear old course completion criteria
496 public function clear_criteria() {
498 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id
));
499 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id
));
501 $this->delete_course_completion_data();
505 * Has the supplied user completed this course
507 * @param int $user_id User's id
510 public function is_course_complete($user_id) {
512 'userid' => $user_id,
513 'course' => $this->course_id
516 $ccompletion = new completion_completion($params);
517 return $ccompletion->is_complete();
521 * Updates (if necessary) the completion state of activity $cm for the given
524 * For manual completion, this function is called when completion is toggled
525 * with $possibleresult set to the target state.
527 * For automatic completion, this function should be called every time a module
528 * does something which might influence a user's completion state. For example,
529 * if a forum provides options for marking itself 'completed' once a user makes
530 * N posts, this function should be called every time a user makes a new post.
531 * [After the post has been saved to the database]. When calling, you do not
532 * need to pass in the new completion state. Instead this function carries out
533 * completion calculation by checking grades and viewed state itself, and
534 * calling the involved module via modulename_get_completion_state() to check
535 * module-specific conditions.
537 * @param stdClass|cm_info $cm Course-module
538 * @param int $possibleresult Expected completion result. If the event that
539 * has just occurred (e.g. add post) can only result in making the activity
540 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
541 * has just occurred (e.g. delete post) can only result in making the activity
542 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
543 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
544 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
545 * processing early if the user's completion state already matches the expected
546 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
547 * must be used; these directly set the specified state.
548 * @param int $userid User ID to be updated. Default 0 = current user
551 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN
, $userid=0) {
554 // Do nothing if completion is not enabled for that activity
555 if (!$this->is_enabled($cm)) {
559 // Get current value of completion state and do nothing if it's same as
560 // the possible result of this change. If the change is to COMPLETE and the
561 // current value is one of the COMPLETE_xx subtypes, ignore that as well
562 $current = $this->get_data($cm, false, $userid);
563 if ($possibleresult == $current->completionstate ||
564 ($possibleresult == COMPLETION_COMPLETE
&&
565 ($current->completionstate
== COMPLETION_COMPLETE_PASS ||
566 $current->completionstate
== COMPLETION_COMPLETE_FAIL
))) {
570 if ($cm->completion
== COMPLETION_TRACKING_MANUAL
) {
571 // For manual tracking we set the result directly
572 switch($possibleresult) {
573 case COMPLETION_COMPLETE
:
574 case COMPLETION_INCOMPLETE
:
575 $newstate = $possibleresult;
578 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
582 // Automatic tracking; get new state
583 $newstate = $this->internal_get_state($cm, $userid, $current);
586 // If changed, update
587 if ($newstate != $current->completionstate
) {
588 $current->completionstate
= $newstate;
589 $current->timemodified
= time();
590 $this->internal_set_data($cm, $current);
595 * Calculates the completion state for an activity and user.
597 * Internal function. Not private, so we can unit-test it.
599 * @param stdClass|cm_info $cm Activity
600 * @param int $userid ID of user
601 * @param stdClass $current Previous completion information from database
604 public function internal_get_state($cm, $userid, $current) {
605 global $USER, $DB, $CFG;
613 if ($cm->completionview
== COMPLETION_VIEW_REQUIRED
&&
614 $current->viewed
== COMPLETION_NOT_VIEWED
) {
616 return COMPLETION_INCOMPLETE
;
619 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
620 if (!isset($cm->modname
)) {
621 $cm->modname
= $DB->get_field('modules', 'name', array('id'=>$cm->module
));
624 $newstate = COMPLETION_COMPLETE
;
627 if (!is_null($cm->completiongradeitemnumber
)) {
628 require_once($CFG->libdir
.'/gradelib.php');
629 $item = grade_item
::fetch(array('courseid'=>$cm->course
, 'itemtype'=>'mod',
630 'itemmodule'=>$cm->modname
, 'iteminstance'=>$cm->instance
,
631 'itemnumber'=>$cm->completiongradeitemnumber
));
633 // Fetch 'grades' (will be one or none)
634 $grades = grade_grade
::fetch_users_grades($item, array($userid), false);
635 if (empty($grades)) {
637 return COMPLETION_INCOMPLETE
;
639 if (count($grades) > 1) {
640 $this->internal_systemerror("Unexpected result: multiple grades for
641 item '{$item->id}', user '{$userid}'");
643 $newstate = self
::internal_get_grade_state($item, reset($grades));
644 if ($newstate == COMPLETION_INCOMPLETE
) {
645 return COMPLETION_INCOMPLETE
;
649 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
650 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
654 if (plugin_supports('mod', $cm->modname
, FEATURE_COMPLETION_HAS_RULES
)) {
655 $function = $cm->modname
.'_get_completion_state';
656 if (!function_exists($function)) {
657 $this->internal_systemerror("Module {$cm->modname} claims to support
658 FEATURE_COMPLETION_HAS_RULES but does not have required
659 {$cm->modname}_get_completion_state function");
661 if (!$function($this->course
, $cm, $userid, COMPLETION_AND
)) {
662 return COMPLETION_INCOMPLETE
;
671 * Marks a module as viewed.
673 * Should be called whenever a module is 'viewed' (it is up to the module how to
674 * determine that). Has no effect if viewing is not set as a completion condition.
676 * Note that this function must be called before you print the page header because
677 * it is possible that the navigation block may depend on it. If you call it after
678 * printing the header, it shows a developer debug warning.
680 * @param stdClass|cm_info $cm Activity
681 * @param int $userid User ID or 0 (default) for current user
684 public function set_module_viewed($cm, $userid=0) {
686 if ($PAGE->headerprinted
) {
687 debugging('set_module_viewed must be called before header is printed',
691 // Don't do anything if view condition is not turned on
692 if ($cm->completionview
== COMPLETION_VIEW_NOT_REQUIRED ||
!$this->is_enabled($cm)) {
696 // Get current completion state
697 $data = $this->get_data($cm, false, $userid);
699 // If we already viewed it, don't do anything
700 if ($data->viewed
== COMPLETION_VIEWED
) {
704 // OK, change state, save it, and update completion
705 $data->viewed
= COMPLETION_VIEWED
;
706 $this->internal_set_data($cm, $data);
707 $this->update_state($cm, COMPLETION_COMPLETE
, $userid);
711 * Determines how much completion data exists for an activity. This is used when
712 * deciding whether completion information should be 'locked' in the module
715 * @param cm_info $cm Activity
716 * @return int The number of users who have completion data stored for this
717 * activity, 0 if none
719 public function count_user_data($cm) {
722 return $DB->get_field_sql("
726 {course_modules_completion}
728 coursemoduleid=? AND completionstate<>0", array($cm->id
));
732 * Determines how much course completion data exists for a course. This is used when
733 * deciding whether completion information should be 'locked' in the completion
734 * settings form and activity completion settings.
736 * @param int $user_id Optionally only get course completion data for a single user
737 * @return int The number of users who have completion data stored for this
740 public function count_course_user_data($user_id = null) {
747 {course_completion_crit_compl}
752 $params = array($this->course_id
);
754 // Limit data to a single user if an ID is supplied
756 $sql .= ' AND userid = ?';
757 $params[] = $user_id;
760 return $DB->get_field_sql($sql, $params);
764 * Check if this course's completion criteria should be locked
768 public function is_course_locked() {
769 return (bool) $this->count_course_user_data();
773 * Deletes all course completion completion data.
775 * Intended to be used when unlocking completion criteria settings.
777 public function delete_course_completion_data() {
780 $DB->delete_records('course_completions', array('course' => $this->course_id
));
781 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id
));
783 // Difficult to find affected users, just purge all completion cache.
784 cache
::make('core', 'completion')->purge();
788 * Deletes all activity and course completion data for an entire course
789 * (the below delete_all_state function does this for a single activity).
791 * Used by course reset page.
793 public function delete_all_completion_data() {
796 // Delete from database.
797 $DB->delete_records_select('course_modules_completion',
798 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
799 array($this->course_id
));
801 // Wipe course completion data too.
802 $this->delete_course_completion_data();
806 * Deletes completion state related to an activity for all users.
808 * Intended for use only when the activity itself is deleted.
810 * @param stdClass|cm_info $cm Activity
812 public function delete_all_state($cm) {
815 // Delete from database
816 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id
));
818 // Check if there is an associated course completion criteria
819 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY
);
821 foreach ($criteria as $criterion) {
822 if ($criterion->moduleinstance
== $cm->id
) {
823 $acriteria = $criterion;
829 // Delete all criteria completions relating to this activity
830 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id
, 'criteriaid' => $acriteria->id
));
831 $DB->delete_records('course_completions', array('course' => $this->course_id
));
834 // Difficult to find affected users, just purge all completion cache.
835 cache
::make('core', 'completion')->purge();
839 * Recalculates completion state related to an activity for all users.
841 * Intended for use if completion conditions change. (This should be avoided
842 * as it may cause some things to become incomplete when they were previously
843 * complete, with the effect - for example - of hiding a later activity that
844 * was previously available.)
846 * Resetting state of manual tickbox has same result as deleting state for
849 * @param stcClass|cm_info $cm Activity
851 public function reset_all_state($cm) {
854 if ($cm->completion
== COMPLETION_TRACKING_MANUAL
) {
855 $this->delete_all_state($cm);
858 // Get current list of users with completion state
859 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id
), '', 'userid');
860 $keepusers = array();
861 foreach ($rs as $rec) {
862 $keepusers[] = $rec->userid
;
866 // Delete all existing state.
867 $this->delete_all_state($cm);
869 // Merge this with list of planned users (according to roles)
870 $trackedusers = $this->get_tracked_users();
871 foreach ($trackedusers as $trackeduser) {
872 $keepusers[] = $trackeduser->id
;
874 $keepusers = array_unique($keepusers);
876 // Recalculate state for each kept user
877 foreach ($keepusers as $keepuser) {
878 $this->update_state($cm, COMPLETION_UNKNOWN
, $keepuser);
883 * Obtains completion data for a particular activity and user (from the
884 * completion cache if available, or by SQL query)
886 * @param stcClass|cm_info $cm Activity; only required field is ->id
887 * @param bool $wholecourse If true (default false) then, when necessary to
888 * fill the cache, retrieves information from the entire course not just for
890 * @param int $userid User ID or 0 (default) for current user
891 * @param array $modinfo Supply the value here - this is used for unit
892 * testing and so that it can be called recursively from within
893 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
894 * Otherwise the method calls get_fast_modinfo itself.
895 * @return object Completion data (record from course_modules_completion)
897 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
898 global $USER, $CFG, $DB;
899 $completioncache = cache
::make('core', 'completion');
906 // See if requested data is present in cache (use cache for current user only).
907 $usecache = $userid == $USER->id
;
908 $cacheddata = array();
910 if (!isset($this->course
->cacherev
)) {
911 $this->course
= get_course($this->course_id
);
913 if ($cacheddata = $completioncache->get($userid . '_' . $this->course
->id
)) {
914 if ($cacheddata['cacherev'] != $this->course
->cacherev
) {
915 // Course structure has been changed since the last caching, forget the cache.
916 $cacheddata = array();
917 } else if (array_key_exists($cm->id
, $cacheddata)) {
918 return $cacheddata[$cm->id
];
923 // Not there, get via SQL
925 // Get whole course data for cache
926 $alldatabycmc = $DB->get_records_sql("
931 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
933 cm.course=? AND cmc.userid=?", array($this->course
->id
, $userid));
938 foreach ($alldatabycmc as $data) {
939 $alldata[$data->coursemoduleid
] = $data;
943 // Get the module info and build up condition info for each one
944 if (empty($modinfo)) {
945 $modinfo = get_fast_modinfo($this->course
, $userid);
947 foreach ($modinfo->cms
as $othercm) {
948 if (array_key_exists($othercm->id
, $alldata)) {
949 $data = $alldata[$othercm->id
];
951 // Row not present counts as 'not complete'
952 $data = new StdClass
;
954 $data->coursemoduleid
= $othercm->id
;
955 $data->userid
= $userid;
956 $data->completionstate
= 0;
958 $data->timemodified
= 0;
960 $cacheddata[$othercm->id
] = $data;
963 if (!isset($cacheddata[$cm->id
])) {
964 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
969 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id
, 'userid'=>$userid));
970 if ($data == false) {
971 // Row not present counts as 'not complete'
972 $data = new StdClass
;
974 $data->coursemoduleid
= $cm->id
;
975 $data->userid
= $userid;
976 $data->completionstate
= 0;
978 $data->timemodified
= 0;
982 $cacheddata[$cm->id
] = $data;
986 $cacheddata['cacherev'] = $this->course
->cacherev
;
987 $completioncache->set($userid . '_' . $this->course
->id
, $cacheddata);
989 return $cacheddata[$cm->id
];
993 * Updates completion data for a particular coursemodule and user (user is
994 * determined from $data).
996 * (Internal function. Not private, so we can unit-test it.)
998 * @param stdClass|cm_info $cm Activity
999 * @param stdClass $data Data about completion for that user
1001 public function internal_set_data($cm, $data) {
1004 $transaction = $DB->start_delegated_transaction();
1006 // Check there isn't really a row
1007 $data->id
= $DB->get_field('course_modules_completion', 'id',
1008 array('coursemoduleid'=>$data->coursemoduleid
, 'userid'=>$data->userid
));
1011 // Didn't exist before, needs creating
1012 $data->id
= $DB->insert_record('course_modules_completion', $data);
1014 // Has real (nonzero) id meaning that a database row exists, update
1015 $DB->update_record('course_modules_completion', $data);
1017 $transaction->allow_commit();
1019 $cmcontext = context_module
::instance($data->coursemoduleid
, MUST_EXIST
);
1020 $coursecontext = $cmcontext->get_parent_context();
1022 // Trigger an event for course module completion changed.
1023 $event = \core\event\course_module_completion_updated
::create(array(
1024 'objectid' => $data->id
,
1025 'context' => $cmcontext,
1026 'relateduserid' => $data->userid
,
1028 'relateduserid' => $data->userid
1031 $event->add_record_snapshot('course_modules_completion', $data);
1034 $completioncache = cache
::make('core', 'completion');
1035 if ($data->userid
== $USER->id
) {
1036 // Update module completion in user's cache.
1037 if (!($cachedata = $completioncache->get($data->userid
. '_' . $cm->course
))
1038 ||
$cachedata['cacherev'] != $this->course
->cacherev
) {
1039 $cachedata = array('cacherev' => $this->course
->cacherev
);
1041 $cachedata[$cm->id
] = $data;
1042 $completioncache->set($data->userid
. '_' . $cm->course
, $cachedata);
1044 // reset modinfo for user (no need to call rebuild_course_cache())
1045 get_fast_modinfo($cm->course
, 0, true);
1047 // Remove another user's completion cache for this course.
1048 $completioncache->delete($data->userid
. '_' . $cm->course
);
1053 * Return whether or not the course has activities with completion enabled.
1055 * @return boolean true when there is at least one activity with completion enabled.
1057 public function has_activities() {
1058 $modinfo = get_fast_modinfo($this->course
);
1059 foreach ($modinfo->get_cms() as $cm) {
1060 if ($cm->completion
!= COMPLETION_TRACKING_NONE
) {
1068 * Obtains a list of activities for which completion is enabled on the
1069 * course. The list is ordered by the section order of those activities.
1071 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1072 * empty array if none
1074 public function get_activities() {
1075 $modinfo = get_fast_modinfo($this->course
);
1077 foreach ($modinfo->get_cms() as $cm) {
1078 if ($cm->completion
!= COMPLETION_TRACKING_NONE
) {
1079 $result[$cm->id
] = $cm;
1086 * Checks to see if the userid supplied has a tracked role in
1089 * @param int $userid User id
1092 public function is_tracked_user($userid) {
1093 return is_enrolled(context_course
::instance($this->course
->id
), $userid, 'moodle/course:isincompletionreports', true);
1097 * Returns the number of users whose progress is tracked in this course.
1099 * Optionally supply a search's where clause, or a group id.
1101 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1102 * @param array $whereparams Where clause params
1103 * @param int $groupid Group id
1104 * @return int Number of tracked users
1106 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1109 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1110 context_course
::instance($this->course
->id
), 'moodle/course:isincompletionreports', $groupid, true);
1111 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1113 $sql .= " WHERE $where";
1116 $params = array_merge($enrolledparams, $whereparams);
1117 return $DB->count_records_sql($sql, $params);
1121 * Return array of users whose progress is tracked in this course.
1123 * Optionally supply a search's where clause, group id, sorting, paging.
1125 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1126 * @param array $whereparams Where clause params (optional)
1127 * @param int $groupid Group ID to restrict to (optional)
1128 * @param string $sort Order by clause (optional)
1129 * @param int $limitfrom Result start (optional)
1130 * @param int $limitnum Result max size (optional)
1131 * @param context $extracontext If set, includes extra user information fields
1132 * as appropriate to display for current user in this context
1133 * @return array Array of user objects with standard user fields
1135 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1136 $sort = '', $limitfrom = '', $limitnum = '', context
$extracontext = null) {
1140 list($enrolledsql, $params) = get_enrolled_sql(
1141 context_course
::instance($this->course
->id
),
1142 'moodle/course:isincompletionreports', $groupid, true);
1144 $allusernames = get_all_user_name_fields(true, 'u');
1145 $sql = 'SELECT u.id, u.idnumber, ' . $allusernames;
1146 if ($extracontext) {
1147 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1149 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1152 $sql .= " AND $where";
1153 $params = array_merge($params, $whereparams);
1157 $sql .= " ORDER BY $sort";
1160 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1164 * Obtains progress information across a course for all users on that course, or
1165 * for all users in a specific group. Intended for use when displaying progress.
1167 * This includes only users who, in course context, have one of the roles for
1168 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1170 * Users are included (in the first array) even if they do not have
1171 * completion progress for any course-module.
1173 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1175 * @param string $where Where clause sql (optional)
1176 * @param array $where_params Where clause params (optional)
1177 * @param int $groupid Group ID or 0 (default)/false for all groups
1178 * @param int $pagesize Number of users to actually return (optional)
1179 * @param int $start User to start at if paging (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 stdClass with ->total and ->start (same as $start) and ->users;
1183 * an array of user objects (like mdl_user id, firstname, lastname)
1184 * containing an additional ->progress array of coursemoduleid => completionstate
1186 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1187 $sort = '', $pagesize = '', $start = '', context
$extracontext = null) {
1190 // Get list of applicable users
1191 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1192 $start, $pagesize, $extracontext);
1194 // Get progress information for these users in groups of 1, 000 (if needed)
1195 // to avoid making the SQL IN too long
1198 foreach ($users as $user) {
1199 $userids[] = $user->id
;
1200 $results[$user->id
] = $user;
1201 $results[$user->id
]->progress
= array();
1204 for($i=0; $i<count($userids); $i+
=1000) {
1205 $blocksize = count($userids)-$i < 1000 ?
count($userids)-$i : 1000;
1207 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1208 array_splice($params, 0, 0, array($this->course
->id
));
1209 $rs = $DB->get_recordset_sql("
1214 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1216 cm.course=? AND cmc.userid $insql", $params);
1217 foreach ($rs as $progress) {
1218 $progress = (object)$progress;
1219 $results[$progress->userid
]->progress
[$progress->coursemoduleid
] = $progress;
1228 * Called by grade code to inform the completion system when a grade has
1229 * been changed. If the changed grade is used to determine completion for
1230 * the course-module, then the completion status will be updated.
1232 * @param stdClass|cm_info $cm Course-module for item that owns grade
1233 * @param grade_item $item Grade item
1234 * @param stdClass $grade
1235 * @param bool $deleted
1237 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1238 // Bail out now if completion is not enabled for course-module, it is enabled
1239 // but is set to manual, grade is not used to compute completion, or this
1240 // is a different numbered grade
1241 if (!$this->is_enabled($cm) ||
1242 $cm->completion
== COMPLETION_TRACKING_MANUAL ||
1243 is_null($cm->completiongradeitemnumber
) ||
1244 $item->itemnumber
!= $cm->completiongradeitemnumber
) {
1248 // What is the expected result based on this grade?
1250 // Grade being deleted, so only change could be to make it incomplete
1251 $possibleresult = COMPLETION_INCOMPLETE
;
1253 $possibleresult = self
::internal_get_grade_state($item, $grade);
1256 // OK, let's update state based on this
1257 $this->update_state($cm, $possibleresult, $grade->userid
);
1261 * Calculates the completion state that would result from a graded item
1262 * (where grade-based completion is turned on) based on the actual grade
1265 * Internal function. Not private, so we can unit-test it.
1267 * @param grade_item $item an instance of grade_item
1268 * @param grade_grade $grade an instance of grade_grade
1269 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1271 public static function internal_get_grade_state($item, $grade) {
1272 // If no grade is supplied or the grade doesn't have an actual value, then
1273 // this is not complete.
1274 if (!$grade ||
(is_null($grade->finalgrade
) && is_null($grade->rawgrade
))) {
1275 return COMPLETION_INCOMPLETE
;
1278 // Conditions to show pass/fail:
1279 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1280 // b) Grade is visible (neither hidden nor hidden-until)
1281 if ($item->gradepass
&& $item->gradepass
> 0.000009 && !$item->hidden
) {
1282 // Use final grade if set otherwise raw grade
1283 $score = !is_null($grade->finalgrade
) ?
$grade->finalgrade
: $grade->rawgrade
;
1285 // We are displaying and tracking pass/fail
1286 if ($score >= $item->gradepass
) {
1287 return COMPLETION_COMPLETE_PASS
;
1289 return COMPLETION_COMPLETE_FAIL
;
1292 // Not displaying pass/fail, so just if there is a grade
1293 if (!is_null($grade->finalgrade
) ||
!is_null($grade->rawgrade
)) {
1294 // Grade exists, so maybe complete now
1295 return COMPLETION_COMPLETE
;
1297 // Grade does not exist, so maybe incomplete now
1298 return COMPLETION_INCOMPLETE
;
1304 * Aggregate activity completion state
1306 * @param int $type Aggregation type (COMPLETION_* constant)
1307 * @param bool $old Old state
1308 * @param bool $new New state
1311 public static function aggregate_completion_states($type, $old, $new) {
1312 if ($type == COMPLETION_AND
) {
1313 return $old && $new;
1315 return $old ||
$new;
1320 * This is to be used only for system errors (things that shouldn't happen)
1321 * and not user-level errors.
1324 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1325 * @throws moodle_exception Exception with the error string as debug info
1327 public function internal_systemerror($error) {
1329 throw new moodle_exception('err_system','completion',
1330 $CFG->wwwroot
.'/course/view.php?id='.$this->course
->id
,null,$error);