MDL-50576 mod_forum: Correct use of movedicussions cap when posting This is a partial...
[moodle.git] / lib / completionlib.php
blob3ff0c28d0d4f28db84f9f47659a54f63dc06b57f
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 * Cache expiry time in seconds (10 minutes)
124 * Completion cacheing
126 define('COMPLETION_CACHE_EXPIRY', 10*60);
129 * Completion details should be ORed together and you should return false if
130 * none apply.
132 define('COMPLETION_OR', false);
134 * Completion details should be ANDed together and you should return true if
135 * none apply
137 define('COMPLETION_AND', true);
140 * Course completion criteria aggregation method.
142 define('COMPLETION_AGGREGATION_ALL', 1);
144 * Course completion criteria aggregation method.
146 define('COMPLETION_AGGREGATION_ANY', 2);
150 * Utility function for checking if the logged in user can view
151 * another's completion data for a particular course
153 * @access public
154 * @param int $userid Completion data's owner
155 * @param mixed $course Course object or Course ID (optional)
156 * @return boolean
158 function completion_can_view_data($userid, $course = null) {
159 global $USER;
161 if (!isloggedin()) {
162 return false;
165 if (!is_object($course)) {
166 $cid = $course;
167 $course = new object();
168 $course->id = $cid;
171 // Check if this is the site course
172 if ($course->id == SITEID) {
173 $course = null;
176 // Check if completion is enabled
177 if ($course) {
178 $cinfo = new completion_info($course);
179 if (!$cinfo->is_enabled()) {
180 return false;
182 } else {
183 if (!completion_info::is_enabled_for_site()) {
184 return false;
188 // Is own user's data?
189 if ($USER->id == $userid) {
190 return true;
193 // Check capabilities
194 $personalcontext = context_user::instance($userid);
196 if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
197 return true;
198 } elseif (has_capability('report/completion:view', $personalcontext)) {
199 return true;
202 if ($course->id) {
203 $coursecontext = context_course::instance($course->id);
204 } else {
205 $coursecontext = context_system::instance();
208 if (has_capability('report/completion:view', $coursecontext)) {
209 return true;
212 return false;
217 * Class represents completion information for a course.
219 * Does not contain any data, so you can safely construct it multiple times
220 * without causing any problems.
222 * @package core
223 * @category completion
224 * @copyright 2008 Sam Marshall
225 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
227 class completion_info {
229 /* @var stdClass Course object passed during construction */
230 private $course;
232 /* @var int Course id */
233 public $course_id;
235 /* @var array Completion criteria {@link completion_info::get_criteria()} */
236 private $criteria;
239 * Return array of aggregation methods
240 * @return array
242 public static function get_aggregation_methods() {
243 return array(
244 COMPLETION_AGGREGATION_ALL => get_string('all'),
245 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
250 * Constructs with course details.
252 * When instantiating a new completion info object you must provide a course
253 * object with at least id, and enablecompletion properties.
255 * @param stdClass $course Moodle course object.
257 public function __construct($course) {
258 $this->course = $course;
259 $this->course_id = $course->id;
263 * Determines whether completion is enabled across entire site.
265 * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
266 * COMPLETION_DISABLED (false) if it's complete
268 public static function is_enabled_for_site() {
269 global $CFG;
270 return !empty($CFG->enablecompletion);
274 * Checks whether completion is enabled in a particular course and possibly
275 * activity.
277 * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
278 * completion enable state.
279 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
280 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
281 * for a course-module.
283 public function is_enabled($cm = null) {
284 global $CFG, $DB;
286 // First check global completion
287 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
288 return COMPLETION_DISABLED;
291 // Load data if we do not have enough
292 if (!isset($this->course->enablecompletion)) {
293 $this->course->enablecompletion = $DB->get_field('course', 'enablecompletion', array('id' => $this->course->id));
296 // Check course completion
297 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
298 return COMPLETION_DISABLED;
301 // If there was no $cm and we got this far, then it's enabled
302 if (!$cm) {
303 return COMPLETION_ENABLED;
306 // Return course-module completion value
307 return $cm->completion;
311 * Displays the 'Your progress' help icon, if completion tracking is enabled.
312 * Just prints the result of display_help_icon().
314 * @deprecated since Moodle 2.0 - Use display_help_icon instead.
316 public function print_help_icon() {
317 print $this->display_help_icon();
321 * Returns the 'Your progress' help icon, if completion tracking is enabled.
323 * @return string HTML code for help icon, or blank if not needed
325 public function display_help_icon() {
326 global $PAGE, $OUTPUT;
327 $result = '';
328 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
329 $result .= html_writer::tag('div', get_string('yourprogress','completion') .
330 $OUTPUT->help_icon('completionicons', 'completion'), array('id' => 'completionprogressid',
331 'class' => 'completionprogress'));
333 return $result;
337 * Get a course completion for a user
339 * @param int $user_id User id
340 * @param int $criteriatype Specific criteria type to return
341 * @return bool|completion_criteria_completion returns false on fail
343 public function get_completion($user_id, $criteriatype) {
344 $completions = $this->get_completions($user_id, $criteriatype);
346 if (empty($completions)) {
347 return false;
348 } elseif (count($completions) > 1) {
349 print_error('multipleselfcompletioncriteria', 'completion');
352 return $completions[0];
356 * Get all course criteria's completion objects for a user
358 * @param int $user_id User id
359 * @param int $criteriatype Specific criteria type to return (optional)
360 * @return array
362 public function get_completions($user_id, $criteriatype = null) {
363 $criterion = $this->get_criteria($criteriatype);
365 $completions = array();
367 foreach ($criterion as $criteria) {
368 $params = array(
369 'course' => $this->course_id,
370 'userid' => $user_id,
371 'criteriaid' => $criteria->id
374 $completion = new completion_criteria_completion($params);
375 $completion->attach_criteria($criteria);
377 $completions[] = $completion;
380 return $completions;
384 * Get completion object for a user and a criteria
386 * @param int $user_id User id
387 * @param completion_criteria $criteria Criteria object
388 * @return completion_criteria_completion
390 public function get_user_completion($user_id, $criteria) {
391 $params = array(
392 'course' => $this->course_id,
393 'userid' => $user_id,
394 'criteriaid' => $criteria->id,
397 $completion = new completion_criteria_completion($params);
398 return $completion;
402 * Check if course has completion criteria set
404 * @return bool Returns true if there are criteria
406 public function has_criteria() {
407 $criteria = $this->get_criteria();
409 return (bool) count($criteria);
413 * Get course completion criteria
415 * @param int $criteriatype Specific criteria type to return (optional)
417 public function get_criteria($criteriatype = null) {
419 // Fill cache if empty
420 if (!is_array($this->criteria)) {
421 global $DB;
423 $params = array(
424 'course' => $this->course->id
427 // Load criteria from database
428 $records = (array)$DB->get_records('course_completion_criteria', $params);
430 // Build array of criteria objects
431 $this->criteria = array();
432 foreach ($records as $record) {
433 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
437 // If after all criteria
438 if ($criteriatype === null) {
439 return $this->criteria;
442 // If we are only after a specific criteria type
443 $criteria = array();
444 foreach ($this->criteria as $criterion) {
446 if ($criterion->criteriatype != $criteriatype) {
447 continue;
450 $criteria[$criterion->id] = $criterion;
453 return $criteria;
457 * Get aggregation method
459 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
460 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
462 public function get_aggregation_method($criteriatype = null) {
463 $params = array(
464 'course' => $this->course_id,
465 'criteriatype' => $criteriatype
468 $aggregation = new completion_aggregation($params);
470 if (!$aggregation->id) {
471 $aggregation->method = COMPLETION_AGGREGATION_ALL;
474 return $aggregation->method;
478 * Get incomplete course completion criteria
480 * @return array
482 public function get_incomplete_criteria() {
483 $incomplete = array();
485 foreach ($this->get_criteria() as $criteria) {
486 if (!$criteria->is_complete()) {
487 $incomplete[] = $criteria;
491 return $incomplete;
495 * Clear old course completion criteria
497 public function clear_criteria() {
498 global $DB;
499 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id));
500 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
502 $this->delete_course_completion_data();
506 * Has the supplied user completed this course
508 * @param int $user_id User's id
509 * @return boolean
511 public function is_course_complete($user_id) {
512 $params = array(
513 'userid' => $user_id,
514 'course' => $this->course_id
517 $ccompletion = new completion_completion($params);
518 return $ccompletion->is_complete();
522 * Updates (if necessary) the completion state of activity $cm for the given
523 * user.
525 * For manual completion, this function is called when completion is toggled
526 * with $possibleresult set to the target state.
528 * For automatic completion, this function should be called every time a module
529 * does something which might influence a user's completion state. For example,
530 * if a forum provides options for marking itself 'completed' once a user makes
531 * N posts, this function should be called every time a user makes a new post.
532 * [After the post has been saved to the database]. When calling, you do not
533 * need to pass in the new completion state. Instead this function carries out
534 * completion calculation by checking grades and viewed state itself, and
535 * calling the involved module via modulename_get_completion_state() to check
536 * module-specific conditions.
538 * @param stdClass|cm_info $cm Course-module
539 * @param int $possibleresult Expected completion result. If the event that
540 * has just occurred (e.g. add post) can only result in making the activity
541 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
542 * has just occurred (e.g. delete post) can only result in making the activity
543 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
544 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
545 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
546 * processing early if the user's completion state already matches the expected
547 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
548 * must be used; these directly set the specified state.
549 * @param int $userid User ID to be updated. Default 0 = current user
550 * @return void
552 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
553 global $USER, $SESSION;
555 // Do nothing if completion is not enabled for that activity
556 if (!$this->is_enabled($cm)) {
557 return;
560 // Get current value of completion state and do nothing if it's same as
561 // the possible result of this change. If the change is to COMPLETE and the
562 // current value is one of the COMPLETE_xx subtypes, ignore that as well
563 $current = $this->get_data($cm, false, $userid);
564 if ($possibleresult == $current->completionstate ||
565 ($possibleresult == COMPLETION_COMPLETE &&
566 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
567 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
568 return;
571 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
572 // For manual tracking we set the result directly
573 switch($possibleresult) {
574 case COMPLETION_COMPLETE:
575 case COMPLETION_INCOMPLETE:
576 $newstate = $possibleresult;
577 break;
578 default:
579 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
582 } else {
583 // Automatic tracking; get new state
584 $newstate = $this->internal_get_state($cm, $userid, $current);
587 // If changed, update
588 if ($newstate != $current->completionstate) {
589 $current->completionstate = $newstate;
590 $current->timemodified = time();
591 $this->internal_set_data($cm, $current);
596 * Calculates the completion state for an activity and user.
598 * Internal function. Not private, so we can unit-test it.
600 * @param stdClass|cm_info $cm Activity
601 * @param int $userid ID of user
602 * @param stdClass $current Previous completion information from database
603 * @return mixed
605 public function internal_get_state($cm, $userid, $current) {
606 global $USER, $DB, $CFG;
608 // Get user ID
609 if (!$userid) {
610 $userid = $USER->id;
613 // Check viewed
614 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
615 $current->viewed == COMPLETION_NOT_VIEWED) {
617 return COMPLETION_INCOMPLETE;
620 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
621 if (!isset($cm->modname)) {
622 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
625 $newstate = COMPLETION_COMPLETE;
627 // Check grade
628 if (!is_null($cm->completiongradeitemnumber)) {
629 require_once($CFG->libdir.'/gradelib.php');
630 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
631 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
632 'itemnumber'=>$cm->completiongradeitemnumber));
633 if ($item) {
634 // Fetch 'grades' (will be one or none)
635 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
636 if (empty($grades)) {
637 // No grade for user
638 return COMPLETION_INCOMPLETE;
640 if (count($grades) > 1) {
641 $this->internal_systemerror("Unexpected result: multiple grades for
642 item '{$item->id}', user '{$userid}'");
644 $newstate = self::internal_get_grade_state($item, reset($grades));
645 if ($newstate == COMPLETION_INCOMPLETE) {
646 return COMPLETION_INCOMPLETE;
649 } else {
650 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
651 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
655 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
656 $function = $cm->modname.'_get_completion_state';
657 if (!function_exists($function)) {
658 $this->internal_systemerror("Module {$cm->modname} claims to support
659 FEATURE_COMPLETION_HAS_RULES but does not have required
660 {$cm->modname}_get_completion_state function");
662 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
663 return COMPLETION_INCOMPLETE;
667 return $newstate;
672 * Marks a module as viewed.
674 * Should be called whenever a module is 'viewed' (it is up to the module how to
675 * determine that). Has no effect if viewing is not set as a completion condition.
677 * Note that this function must be called before you print the page header because
678 * it is possible that the navigation block may depend on it. If you call it after
679 * printing the header, it shows a developer debug warning.
681 * @param stdClass|cm_info $cm Activity
682 * @param int $userid User ID or 0 (default) for current user
683 * @return void
685 public function set_module_viewed($cm, $userid=0) {
686 global $PAGE;
687 if ($PAGE->headerprinted) {
688 debugging('set_module_viewed must be called before header is printed',
689 DEBUG_DEVELOPER);
692 // Don't do anything if view condition is not turned on
693 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
694 return;
697 // Get current completion state
698 $data = $this->get_data($cm, false, $userid);
700 // If we already viewed it, don't do anything
701 if ($data->viewed == COMPLETION_VIEWED) {
702 return;
705 // OK, change state, save it, and update completion
706 $data->viewed = COMPLETION_VIEWED;
707 $this->internal_set_data($cm, $data);
708 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
712 * Determines how much completion data exists for an activity. This is used when
713 * deciding whether completion information should be 'locked' in the module
714 * editing form.
716 * @param cm_info $cm Activity
717 * @return int The number of users who have completion data stored for this
718 * activity, 0 if none
720 public function count_user_data($cm) {
721 global $DB;
723 return $DB->get_field_sql("
724 SELECT
725 COUNT(1)
726 FROM
727 {course_modules_completion}
728 WHERE
729 coursemoduleid=? AND completionstate<>0", array($cm->id));
733 * Determines how much course completion data exists for a course. This is used when
734 * deciding whether completion information should be 'locked' in the completion
735 * settings form and activity completion settings.
737 * @param int $user_id Optionally only get course completion data for a single user
738 * @return int The number of users who have completion data stored for this
739 * course, 0 if none
741 public function count_course_user_data($user_id = null) {
742 global $DB;
744 $sql = '
745 SELECT
746 COUNT(1)
747 FROM
748 {course_completion_crit_compl}
749 WHERE
750 course = ?
753 $params = array($this->course_id);
755 // Limit data to a single user if an ID is supplied
756 if ($user_id) {
757 $sql .= ' AND userid = ?';
758 $params[] = $user_id;
761 return $DB->get_field_sql($sql, $params);
765 * Check if this course's completion criteria should be locked
767 * @return boolean
769 public function is_course_locked() {
770 return (bool) $this->count_course_user_data();
774 * Deletes all course completion completion data.
776 * Intended to be used when unlocking completion criteria settings.
778 public function delete_course_completion_data() {
779 global $DB;
781 $DB->delete_records('course_completions', array('course' => $this->course_id));
782 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
786 * Deletes all activity and course completion data for an entire course
787 * (the below delete_all_state function does this for a single activity).
789 * Used by course reset page.
791 public function delete_all_completion_data() {
792 global $DB, $SESSION;
794 // Delete from database.
795 $DB->delete_records_select('course_modules_completion',
796 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
797 array($this->course_id));
799 // Reset cache for current user.
800 if (isset($SESSION->completioncache) &&
801 array_key_exists($this->course_id, $SESSION->completioncache)) {
803 unset($SESSION->completioncache[$this->course_id]);
806 // Wipe course completion data too.
807 $this->delete_course_completion_data();
811 * Deletes completion state related to an activity for all users.
813 * Intended for use only when the activity itself is deleted.
815 * @param stdClass|cm_info $cm Activity
817 public function delete_all_state($cm) {
818 global $SESSION, $DB;
820 // Delete from database
821 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
823 // Erase cache data for current user if applicable
824 if (isset($SESSION->completioncache) &&
825 array_key_exists($cm->course, $SESSION->completioncache) &&
826 array_key_exists($cm->id, $SESSION->completioncache[$cm->course])) {
828 unset($SESSION->completioncache[$cm->course][$cm->id]);
831 // Check if there is an associated course completion criteria
832 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
833 $acriteria = false;
834 foreach ($criteria as $criterion) {
835 if ($criterion->moduleinstance == $cm->id) {
836 $acriteria = $criterion;
837 break;
841 if ($acriteria) {
842 // Delete all criteria completions relating to this activity
843 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
844 $DB->delete_records('course_completions', array('course' => $this->course_id));
849 * Recalculates completion state related to an activity for all users.
851 * Intended for use if completion conditions change. (This should be avoided
852 * as it may cause some things to become incomplete when they were previously
853 * complete, with the effect - for example - of hiding a later activity that
854 * was previously available.)
856 * Resetting state of manual tickbox has same result as deleting state for
857 * it.
859 * @param stcClass|cm_info $cm Activity
861 public function reset_all_state($cm) {
862 global $DB;
864 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
865 $this->delete_all_state($cm);
866 return;
868 // Get current list of users with completion state
869 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
870 $keepusers = array();
871 foreach ($rs as $rec) {
872 $keepusers[] = $rec->userid;
874 $rs->close();
876 // Delete all existing state [also clears session cache for current user]
877 $this->delete_all_state($cm);
879 // Merge this with list of planned users (according to roles)
880 $trackedusers = $this->get_tracked_users();
881 foreach ($trackedusers as $trackeduser) {
882 $keepusers[] = $trackeduser->id;
884 $keepusers = array_unique($keepusers);
886 // Recalculate state for each kept user
887 foreach ($keepusers as $keepuser) {
888 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
893 * Obtains completion data for a particular activity and user (from the
894 * session cache if available, or by SQL query)
896 * @param stcClass|cm_info $cm Activity; only required field is ->id
897 * @param bool $wholecourse If true (default false) then, when necessary to
898 * fill the cache, retrieves information from the entire course not just for
899 * this one activity
900 * @param int $userid User ID or 0 (default) for current user
901 * @param array $modinfo Supply the value here - this is used for unit
902 * testing and so that it can be called recursively from within
903 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
904 * Otherwise the method calls get_fast_modinfo itself.
905 * @return object Completion data (record from course_modules_completion)
907 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
908 global $USER, $CFG, $SESSION, $DB;
910 // Get user ID
911 if (!$userid) {
912 $userid = $USER->id;
915 // Is this the current user?
916 $currentuser = $userid==$USER->id;
918 if ($currentuser && is_object($SESSION)) {
919 // Make sure cache is present and is for current user (loginas
920 // changes this)
921 if (!isset($SESSION->completioncache) || $SESSION->completioncacheuserid!=$USER->id) {
922 $SESSION->completioncache = array();
923 $SESSION->completioncacheuserid = $USER->id;
925 // Expire any old data from cache
926 foreach ($SESSION->completioncache as $courseid=>$activities) {
927 if (empty($activities['updated']) || $activities['updated'] < time()-COMPLETION_CACHE_EXPIRY) {
928 unset($SESSION->completioncache[$courseid]);
931 // See if requested data is present, if so use cache to get it
932 if (isset($SESSION->completioncache) &&
933 array_key_exists($this->course->id, $SESSION->completioncache) &&
934 array_key_exists($cm->id, $SESSION->completioncache[$this->course->id])) {
935 return $SESSION->completioncache[$this->course->id][$cm->id];
939 // Not there, get via SQL
940 if ($currentuser && $wholecourse) {
941 // Get whole course data for cache
942 $alldatabycmc = $DB->get_records_sql("
943 SELECT
944 cmc.*
945 FROM
946 {course_modules} cm
947 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
948 WHERE
949 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
951 // Reindex by cm id
952 $alldata = array();
953 if ($alldatabycmc) {
954 foreach ($alldatabycmc as $data) {
955 $alldata[$data->coursemoduleid] = $data;
959 // Get the module info and build up condition info for each one
960 if (empty($modinfo)) {
961 $modinfo = get_fast_modinfo($this->course, $userid);
963 foreach ($modinfo->cms as $othercm) {
964 if (array_key_exists($othercm->id, $alldata)) {
965 $data = $alldata[$othercm->id];
966 } else {
967 // Row not present counts as 'not complete'
968 $data = new StdClass;
969 $data->id = 0;
970 $data->coursemoduleid = $othercm->id;
971 $data->userid = $userid;
972 $data->completionstate = 0;
973 $data->viewed = 0;
974 $data->timemodified = 0;
976 $SESSION->completioncache[$this->course->id][$othercm->id] = $data;
978 $SESSION->completioncache[$this->course->id]['updated'] = time();
980 if (!isset($SESSION->completioncache[$this->course->id][$cm->id])) {
981 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
983 return $SESSION->completioncache[$this->course->id][$cm->id];
985 } else {
986 // Get single record
987 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
988 if ($data == false) {
989 // Row not present counts as 'not complete'
990 $data = new StdClass;
991 $data->id = 0;
992 $data->coursemoduleid = $cm->id;
993 $data->userid = $userid;
994 $data->completionstate = 0;
995 $data->viewed = 0;
996 $data->timemodified = 0;
999 // Put in cache
1000 if ($currentuser) {
1001 $SESSION->completioncache[$this->course->id][$cm->id] = $data;
1002 // For single updates, only set date if it was empty before
1003 if (empty($SESSION->completioncache[$this->course->id]['updated'])) {
1004 $SESSION->completioncache[$this->course->id]['updated'] = time();
1009 return $data;
1013 * Updates completion data for a particular coursemodule and user (user is
1014 * determined from $data).
1016 * (Internal function. Not private, so we can unit-test it.)
1018 * @param stdClass|cm_info $cm Activity
1019 * @param stdClass $data Data about completion for that user
1021 public function internal_set_data($cm, $data) {
1022 global $USER, $SESSION, $DB;
1024 $transaction = $DB->start_delegated_transaction();
1025 if (!$data->id) {
1026 // Check there isn't really a row
1027 $data->id = $DB->get_field('course_modules_completion', 'id',
1028 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
1030 if (!$data->id) {
1031 // Didn't exist before, needs creating
1032 $data->id = $DB->insert_record('course_modules_completion', $data);
1033 } else {
1034 // Has real (nonzero) id meaning that a database row exists, update
1035 $DB->update_record('course_modules_completion', $data);
1037 $transaction->allow_commit();
1039 $cmcontext = context_module::instance($data->coursemoduleid, MUST_EXIST);
1040 $coursecontext = $cmcontext->get_parent_context();
1042 // Trigger an event for course module completion changed.
1043 $event = \core\event\course_module_completion_updated::create(array(
1044 'objectid' => $data->id,
1045 'context' => $cmcontext,
1046 'relateduserid' => $data->userid,
1047 'other' => array(
1048 'relateduserid' => $data->userid
1051 $event->add_record_snapshot('course_modules_completion', $data);
1052 $event->trigger();
1054 if ($data->userid == $USER->id) {
1055 $SESSION->completioncache[$cm->course][$cm->id] = $data;
1056 // reset modinfo for user (no need to call rebuild_course_cache())
1057 get_fast_modinfo($cm->course, 0, true);
1062 * Return whether or not the course has activities with completion enabled.
1064 * @return boolean true when there is at least one activity with completion enabled.
1066 public function has_activities() {
1067 $modinfo = get_fast_modinfo($this->course);
1068 foreach ($modinfo->get_cms() as $cm) {
1069 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1070 return true;
1073 return false;
1077 * Obtains a list of activities for which completion is enabled on the
1078 * course. The list is ordered by the section order of those activities.
1080 * @return cm_info[] Array from $cmid => $cm of all activities with completion enabled,
1081 * empty array if none
1083 public function get_activities() {
1084 $modinfo = get_fast_modinfo($this->course);
1085 $result = array();
1086 foreach ($modinfo->get_cms() as $cm) {
1087 if ($cm->completion != COMPLETION_TRACKING_NONE) {
1088 $result[$cm->id] = $cm;
1091 return $result;
1095 * Checks to see if the userid supplied has a tracked role in
1096 * this course
1098 * @param int $userid User id
1099 * @return bool
1101 public function is_tracked_user($userid) {
1102 return is_enrolled(context_course::instance($this->course->id), $userid, 'moodle/course:isincompletionreports', true);
1106 * Returns the number of users whose progress is tracked in this course.
1108 * Optionally supply a search's where clause, or a group id.
1110 * @param string $where Where clause sql (use 'u.whatever' for user table fields)
1111 * @param array $whereparams Where clause params
1112 * @param int $groupid Group id
1113 * @return int Number of tracked users
1115 public function get_num_tracked_users($where = '', $whereparams = array(), $groupid = 0) {
1116 global $DB;
1118 list($enrolledsql, $enrolledparams) = get_enrolled_sql(
1119 context_course::instance($this->course->id), 'moodle/course:isincompletionreports', $groupid, true);
1120 $sql = 'SELECT COUNT(eu.id) FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1121 if ($where) {
1122 $sql .= " WHERE $where";
1125 $params = array_merge($enrolledparams, $whereparams);
1126 return $DB->count_records_sql($sql, $params);
1130 * Return array of users whose progress is tracked in this course.
1132 * Optionally supply a search's where clause, group id, sorting, paging.
1134 * @param string $where Where clause sql, referring to 'u.' fields (optional)
1135 * @param array $whereparams Where clause params (optional)
1136 * @param int $groupid Group ID to restrict to (optional)
1137 * @param string $sort Order by clause (optional)
1138 * @param int $limitfrom Result start (optional)
1139 * @param int $limitnum Result max size (optional)
1140 * @param context $extracontext If set, includes extra user information fields
1141 * as appropriate to display for current user in this context
1142 * @return array Array of user objects with standard user fields
1144 public function get_tracked_users($where = '', $whereparams = array(), $groupid = 0,
1145 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1147 global $DB;
1149 list($enrolledsql, $params) = get_enrolled_sql(
1150 context_course::instance($this->course->id),
1151 'moodle/course:isincompletionreports', $groupid, true);
1153 $allusernames = get_all_user_name_fields(true, 'u');
1154 $sql = 'SELECT u.id, u.idnumber, ' . $allusernames;
1155 if ($extracontext) {
1156 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1158 $sql .= ' FROM (' . $enrolledsql . ') eu JOIN {user} u ON u.id = eu.id';
1160 if ($where) {
1161 $sql .= " AND $where";
1162 $params = array_merge($params, $whereparams);
1165 if ($sort) {
1166 $sql .= " ORDER BY $sort";
1169 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1173 * Obtains progress information across a course for all users on that course, or
1174 * for all users in a specific group. Intended for use when displaying progress.
1176 * This includes only users who, in course context, have one of the roles for
1177 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1179 * Users are included (in the first array) even if they do not have
1180 * completion progress for any course-module.
1182 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1183 * last name
1184 * @param string $where Where clause sql (optional)
1185 * @param array $where_params Where clause params (optional)
1186 * @param int $groupid Group ID or 0 (default)/false for all groups
1187 * @param int $pagesize Number of users to actually return (optional)
1188 * @param int $start User to start at if paging (optional)
1189 * @param context $extracontext If set, includes extra user information fields
1190 * as appropriate to display for current user in this context
1191 * @return stdClass with ->total and ->start (same as $start) and ->users;
1192 * an array of user objects (like mdl_user id, firstname, lastname)
1193 * containing an additional ->progress array of coursemoduleid => completionstate
1195 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1196 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1197 global $CFG, $DB;
1199 // Get list of applicable users
1200 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1201 $start, $pagesize, $extracontext);
1203 // Get progress information for these users in groups of 1, 000 (if needed)
1204 // to avoid making the SQL IN too long
1205 $results = array();
1206 $userids = array();
1207 foreach ($users as $user) {
1208 $userids[] = $user->id;
1209 $results[$user->id] = $user;
1210 $results[$user->id]->progress = array();
1213 for($i=0; $i<count($userids); $i+=1000) {
1214 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1216 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1217 array_splice($params, 0, 0, array($this->course->id));
1218 $rs = $DB->get_recordset_sql("
1219 SELECT
1220 cmc.*
1221 FROM
1222 {course_modules} cm
1223 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1224 WHERE
1225 cm.course=? AND cmc.userid $insql", $params);
1226 foreach ($rs as $progress) {
1227 $progress = (object)$progress;
1228 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1230 $rs->close();
1233 return $results;
1237 * Called by grade code to inform the completion system when a grade has
1238 * been changed. If the changed grade is used to determine completion for
1239 * the course-module, then the completion status will be updated.
1241 * @param stdClass|cm_info $cm Course-module for item that owns grade
1242 * @param grade_item $item Grade item
1243 * @param stdClass $grade
1244 * @param bool $deleted
1246 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1247 // Bail out now if completion is not enabled for course-module, it is enabled
1248 // but is set to manual, grade is not used to compute completion, or this
1249 // is a different numbered grade
1250 if (!$this->is_enabled($cm) ||
1251 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1252 is_null($cm->completiongradeitemnumber) ||
1253 $item->itemnumber != $cm->completiongradeitemnumber) {
1254 return;
1257 // What is the expected result based on this grade?
1258 if ($deleted) {
1259 // Grade being deleted, so only change could be to make it incomplete
1260 $possibleresult = COMPLETION_INCOMPLETE;
1261 } else {
1262 $possibleresult = self::internal_get_grade_state($item, $grade);
1265 // OK, let's update state based on this
1266 $this->update_state($cm, $possibleresult, $grade->userid);
1270 * Calculates the completion state that would result from a graded item
1271 * (where grade-based completion is turned on) based on the actual grade
1272 * and settings.
1274 * Internal function. Not private, so we can unit-test it.
1276 * @param grade_item $item an instance of grade_item
1277 * @param grade_grade $grade an instance of grade_grade
1278 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1280 public static function internal_get_grade_state($item, $grade) {
1281 // If no grade is supplied or the grade doesn't have an actual value, then
1282 // this is not complete.
1283 if (!$grade || (is_null($grade->finalgrade) && is_null($grade->rawgrade))) {
1284 return COMPLETION_INCOMPLETE;
1287 // Conditions to show pass/fail:
1288 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1289 // b) Grade is visible (neither hidden nor hidden-until)
1290 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1291 // Use final grade if set otherwise raw grade
1292 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1294 // We are displaying and tracking pass/fail
1295 if ($score >= $item->gradepass) {
1296 return COMPLETION_COMPLETE_PASS;
1297 } else {
1298 return COMPLETION_COMPLETE_FAIL;
1300 } else {
1301 // Not displaying pass/fail, so just if there is a grade
1302 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1303 // Grade exists, so maybe complete now
1304 return COMPLETION_COMPLETE;
1305 } else {
1306 // Grade does not exist, so maybe incomplete now
1307 return COMPLETION_INCOMPLETE;
1313 * Aggregate activity completion state
1315 * @param int $type Aggregation type (COMPLETION_* constant)
1316 * @param bool $old Old state
1317 * @param bool $new New state
1318 * @return bool
1320 public static function aggregate_completion_states($type, $old, $new) {
1321 if ($type == COMPLETION_AND) {
1322 return $old && $new;
1323 } else {
1324 return $old || $new;
1329 * This is to be used only for system errors (things that shouldn't happen)
1330 * and not user-level errors.
1332 * @global type $CFG
1333 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1334 * @throws moodle_exception Exception with the error string as debug info
1336 public function internal_systemerror($error) {
1337 global $CFG;
1338 throw new moodle_exception('err_system','completion',
1339 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1343 * For testing only. Wipes information cached in user session.
1345 public static function wipe_session_cache() {
1346 global $SESSION;
1347 unset($SESSION->completioncache);
1348 unset($SESSION->completioncacheuserid);