Merge branch 'MDL-35147_22' of git://github.com/timhunt/moodle into MOODLE_22_STABLE
[moodle.git] / lib / completionlib.php
blobf48ec231014871db5fbe8127c83430cc3a863c62
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Contains a class used for tracking whether activities have been completed
20 * by students ('completion')
22 * Completion top-level options (admin setting enablecompletion)
24 * @package core
25 * @subpackage completion
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
32 require_once $CFG->libdir.'/completion/completion_aggregation.php';
33 require_once $CFG->libdir.'/completion/completion_criteria.php';
34 require_once $CFG->libdir.'/completion/completion_completion.php';
35 require_once $CFG->libdir.'/completion/completion_criteria_completion.php';
38 /** The completion system is enabled in this site/course */
39 define('COMPLETION_ENABLED', 1);
40 /** The completion system is not enabled in this site/course */
41 define('COMPLETION_DISABLED', 0);
43 // Completion tracking options per-activity (course_modules/completion)
45 /** Completion tracking is disabled for this activity */
46 define('COMPLETION_TRACKING_NONE', 0);
47 /** Manual completion tracking (user ticks box) is enabled for this activity */
48 define('COMPLETION_TRACKING_MANUAL', 1);
49 /** Automatic completion tracking (system ticks box) is enabled for this activity */
50 define('COMPLETION_TRACKING_AUTOMATIC', 2);
52 // Completion state values (course_modules_completion/completionstate)
54 /** The user has not completed this activity. */
55 define('COMPLETION_INCOMPLETE', 0);
56 /** The user has completed this activity. It is not specified whether they have
57 * passed or failed it. */
58 define('COMPLETION_COMPLETE', 1);
59 /** The user has completed this activity with a grade above the pass mark. */
60 define('COMPLETION_COMPLETE_PASS', 2);
61 /** The user has completed this activity but their grade is less than the pass mark */
62 define('COMPLETION_COMPLETE_FAIL', 3);
64 // Completion effect changes (used only in update_state)
66 /** The effect of this change to completion status is unknown. */
67 define('COMPLETION_UNKNOWN', -1);
68 /** The user's grade has changed, so their new state might be
69 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL. */
70 // TODO Is this useful?
71 define('COMPLETION_GRADECHANGE', -2);
73 // Whether view is required to create an activity (course_modules/completionview)
75 /** User must view this activity */
76 define('COMPLETION_VIEW_REQUIRED', 1);
77 /** User does not need to view this activity */
78 define('COMPLETION_VIEW_NOT_REQUIRED', 0);
80 // Completion viewed state (course_modules_completion/viewed)
82 /** User has viewed this activity */
83 define('COMPLETION_VIEWED', 1);
84 /** User has not viewed this activity */
85 define('COMPLETION_NOT_VIEWED', 0);
87 // Completion cacheing
89 /** Cache expiry time in seconds (10 minutes) */
90 define('COMPLETION_CACHE_EXPIRY', 10*60);
92 // Combining completion condition. This is also the value you should return
93 // if you don't have any applicable conditions. Used for activity completion.
94 /** Completion details should be ORed together and you should return false if
95 none apply */
96 define('COMPLETION_OR', false);
97 /** Completion details should be ANDed together and you should return true if
98 none apply */
99 define('COMPLETION_AND', true);
101 // Course completion criteria aggregation methods
102 define('COMPLETION_AGGREGATION_ALL', 1);
103 define('COMPLETION_AGGREGATION_ANY', 2);
107 * Class represents completion information for a course.
109 * Does not contain any data, so you can safely construct it multiple times
110 * without causing any problems.
112 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
113 * @package moodlecore
115 class completion_info {
117 * Course object passed during construction
118 * @access private
119 * @var object
121 private $course;
124 * Course id
125 * @access public
126 * @var int
128 public $course_id;
131 * Completion criteria
132 * @access private
133 * @var array
134 * @see completion_info->get_criteria()
136 private $criteria;
139 * Return array of aggregation methods
140 * @access public
141 * @return array
143 public static function get_aggregation_methods() {
144 return array(
145 COMPLETION_AGGREGATION_ALL => get_string('all'),
146 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
151 * Constructs with course details.
153 * @param object $course Moodle course object. Must have at least ->id, ->enablecompletion
155 public function __construct($course) {
156 $this->course = $course;
157 $this->course_id = $course->id;
161 * Determines whether completion is enabled across entire site.
163 * Static function.
165 * @global object
166 * @return int COMPLETION_ENABLED (true) if completion is enabled for the site,
167 * COMPLETION_DISABLED (false) if it's complete
169 public static function is_enabled_for_site() {
170 global $CFG;
171 return !empty($CFG->enablecompletion);
175 * Checks whether completion is enabled in a particular course and possibly
176 * activity.
178 * @global object
179 * @uses COMPLETION_DISABLED
180 * @uses COMPLETION_ENABLED
181 * @param object $cm Course-module object. If not specified, returns the course
182 * completion enable state.
183 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
184 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
185 * for a course-module.
187 public function is_enabled($cm=null) {
188 global $CFG, $DB;
190 // First check global completion
191 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
192 return COMPLETION_DISABLED;
195 // Load data if we do not have enough
196 if (!isset($this->course->enablecompletion)) {
197 $this->course->enablecompletion = $DB->get_field('course', 'enablecompletion', array('id' => $this->course->id));
200 // Check course completion
201 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
202 return COMPLETION_DISABLED;
205 // If there was no $cm and we got this far, then it's enabled
206 if (!$cm) {
207 return COMPLETION_ENABLED;
210 // Return course-module completion value
211 return $cm->completion;
215 * Displays the 'Your progress' help icon, if completion tracking is enabled.
216 * Just prints the result of display_help_icon().
217 * @deprecated Use display_help_icon instead.
218 * @return void
220 public function print_help_icon() {
221 print $this->display_help_icon();
225 * Returns the 'Your progress' help icon, if completion tracking is enabled.
226 * @global object
227 * @return string HTML code for help icon, or blank if not needed
229 public function display_help_icon() {
230 global $PAGE, $OUTPUT;
231 $result = '';
232 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
233 $result .= '<span id = "completionprogressid" class="completionprogress">'.get_string('yourprogress','completion').' ';
234 $result .= $OUTPUT->help_icon('completionicons', 'completion');
235 $result .= '</span>';
237 return $result;
241 * Get a course completion for a user
242 * @access public
243 * @param $user_id int User id
244 * @param $criteriatype int Specific criteria type to return
245 * @return false|completion_criteria_completion
247 public function get_completion($user_id, $criteriatype) {
248 $completions = $this->get_completions($user_id, $criteriatype);
250 if (empty($completions)) {
251 return false;
252 } elseif (count($completions) > 1) {
253 print_error('multipleselfcompletioncriteria', 'completion');
256 return $completions[0];
260 * Get all course criteria's completion objects for a user
261 * @access public
262 * @param $user_id int User id
263 * @param $criteriatype int optional Specific criteria type to return
264 * @return array
266 public function get_completions($user_id, $criteriatype = null) {
267 $criterion = $this->get_criteria($criteriatype);
269 $completions = array();
271 foreach ($criterion as $criteria) {
272 $params = array(
273 'course' => $this->course_id,
274 'userid' => $user_id,
275 'criteriaid' => $criteria->id
278 $completion = new completion_criteria_completion($params);
279 $completion->attach_criteria($criteria);
281 $completions[] = $completion;
284 return $completions;
288 * Get completion object for a user and a criteria
289 * @access public
290 * @param $user_id int User id
291 * @param $criteria completion_criteria Criteria object
292 * @return completion_criteria_completion
294 public function get_user_completion($user_id, $criteria) {
295 $params = array(
296 'course' => $this->course_id,
297 'userid' => $user_id,
298 'criteriaid' => $criteria->id,
301 $completion = new completion_criteria_completion($params);
302 return $completion;
306 * Check if course has completion criteria set
308 * @access public
309 * @return bool
311 public function has_criteria() {
312 $criteria = $this->get_criteria();
314 return (bool) count($criteria);
319 * Get course completion criteria
320 * @access public
321 * @param $criteriatype int optional Specific criteria type to return
322 * @return void
324 public function get_criteria($criteriatype = null) {
326 // Fill cache if empty
327 if (!is_array($this->criteria)) {
328 global $DB;
330 $params = array(
331 'course' => $this->course->id
334 // Load criteria from database
335 $records = (array)$DB->get_records('course_completion_criteria', $params);
337 // Build array of criteria objects
338 $this->criteria = array();
339 foreach ($records as $record) {
340 $this->criteria[$record->id] = completion_criteria::factory((array)$record);
344 // If after all criteria
345 if ($criteriatype === null) {
346 return $this->criteria;
349 // If we are only after a specific criteria type
350 $criteria = array();
351 foreach ($this->criteria as $criterion) {
353 if ($criterion->criteriatype != $criteriatype) {
354 continue;
357 $criteria[$criterion->id] = $criterion;
360 return $criteria;
364 * Get aggregation method
365 * @access public
366 * @param $criteriatype int optional If none supplied, get overall aggregation method
367 * @return int
369 public function get_aggregation_method($criteriatype = null) {
370 $params = array(
371 'course' => $this->course_id,
372 'criteriatype' => $criteriatype
375 $aggregation = new completion_aggregation($params);
377 if (!$aggregation->id) {
378 $aggregation->method = COMPLETION_AGGREGATION_ALL;
381 return $aggregation->method;
385 * Get incomplete course completion criteria
386 * @access public
387 * @return void
389 public function get_incomplete_criteria() {
390 $incomplete = array();
392 foreach ($this->get_criteria() as $criteria) {
393 if (!$criteria->is_complete()) {
394 $incomplete[] = $criteria;
398 return $incomplete;
402 * Clear old course completion criteria
404 public function clear_criteria() {
405 global $DB;
406 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id));
407 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
409 $this->delete_course_completion_data();
413 * Has the supplied user completed this course
414 * @access public
415 * @param $user_id int User's id
416 * @return boolean
418 public function is_course_complete($user_id) {
419 $params = array(
420 'userid' => $user_id,
421 'course' => $this->course_id
424 $ccompletion = new completion_completion($params);
425 return $ccompletion->is_complete();
429 * Updates (if necessary) the completion state of activity $cm for the given
430 * user.
432 * For manual completion, this function is called when completion is toggled
433 * with $possibleresult set to the target state.
435 * For automatic completion, this function should be called every time a module
436 * does something which might influence a user's completion state. For example,
437 * if a forum provides options for marking itself 'completed' once a user makes
438 * N posts, this function should be called every time a user makes a new post.
439 * [After the post has been saved to the database]. When calling, you do not
440 * need to pass in the new completion state. Instead this function carries out
441 * completion calculation by checking grades and viewed state itself, and
442 * calling the involved module via modulename_get_completion_state() to check
443 * module-specific conditions.
445 * @global object
446 * @global object
447 * @uses COMPLETION_COMPLETE
448 * @uses COMPLETION_INCOMPLETE
449 * @uses COMPLETION_COMPLETE_PASS
450 * @uses COMPLETION_COMPLETE_FAIL
451 * @uses COMPLETION_TRACKING_MANUAL
452 * @param object $cm Course-module
453 * @param int $possibleresult Expected completion result. If the event that
454 * has just occurred (e.g. add post) can only result in making the activity
455 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
456 * has just occurred (e.g. delete post) can only result in making the activity
457 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
458 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
459 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
460 * processing early if the user's completion state already matches the expected
461 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
462 * must be used; these directly set the specified state.
463 * @param int $userid User ID to be updated. Default 0 = current user
464 * @return void
466 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
467 global $USER, $SESSION;
469 // Do nothing if completion is not enabled for that activity
470 if (!$this->is_enabled($cm)) {
471 return;
474 // Get current value of completion state and do nothing if it's same as
475 // the possible result of this change. If the change is to COMPLETE and the
476 // current value is one of the COMPLETE_xx subtypes, ignore that as well
477 $current = $this->get_data($cm, false, $userid);
478 if ($possibleresult == $current->completionstate ||
479 ($possibleresult == COMPLETION_COMPLETE &&
480 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
481 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
482 return;
485 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
486 // For manual tracking we set the result directly
487 switch($possibleresult) {
488 case COMPLETION_COMPLETE:
489 case COMPLETION_INCOMPLETE:
490 $newstate = $possibleresult;
491 break;
492 default:
493 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
496 } else {
497 // Automatic tracking; get new state
498 $newstate = $this->internal_get_state($cm, $userid, $current);
501 // If changed, update
502 if ($newstate != $current->completionstate) {
503 $current->completionstate = $newstate;
504 $current->timemodified = time();
505 $this->internal_set_data($cm, $current);
510 * Calculates the completion state for an activity and user.
512 * Internal function. Not private, so we can unit-test it.
514 * @global object
515 * @global object
516 * @global object
517 * @uses COMPLETION_VIEW_REQUIRED
518 * @uses COMPLETION_NOT_VIEWED
519 * @uses COMPLETION_INCOMPLETE
520 * @uses FEATURE_COMPLETION_HAS_RULES
521 * @uses COMPLETION_COMPLETE
522 * @uses COMPLETION_AND
523 * @param object $cm Activity
524 * @param int $userid ID of user
525 * @param object $current Previous completion information from database
526 * @return mixed
528 function internal_get_state($cm, $userid, $current) {
529 global $USER, $DB, $CFG;
531 // Get user ID
532 if (!$userid) {
533 $userid = $USER->id;
536 // Check viewed
537 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
538 $current->viewed == COMPLETION_NOT_VIEWED) {
540 return COMPLETION_INCOMPLETE;
543 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
544 if (!isset($cm->modname)) {
545 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
548 $newstate = COMPLETION_COMPLETE;
550 // Check grade
551 if (!is_null($cm->completiongradeitemnumber)) {
552 require_once($CFG->libdir.'/gradelib.php');
553 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
554 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
555 'itemnumber'=>$cm->completiongradeitemnumber));
556 if ($item) {
557 // Fetch 'grades' (will be one or none)
558 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
559 if (empty($grades)) {
560 // No grade for user
561 return COMPLETION_INCOMPLETE;
563 if (count($grades) > 1) {
564 $this->internal_systemerror("Unexpected result: multiple grades for
565 item '{$item->id}', user '{$userid}'");
567 $newstate = $this->internal_get_grade_state($item, reset($grades));
568 if ($newstate == COMPLETION_INCOMPLETE) {
569 return COMPLETION_INCOMPLETE;
572 } else {
573 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
574 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
578 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
579 $function = $cm->modname.'_get_completion_state';
580 if (!function_exists($function)) {
581 $this->internal_systemerror("Module {$cm->modname} claims to support
582 FEATURE_COMPLETION_HAS_RULES but does not have required
583 {$cm->modname}_get_completion_state function");
585 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
586 return COMPLETION_INCOMPLETE;
590 return $newstate;
596 * Marks a module as viewed.
598 * Should be called whenever a module is 'viewed' (it is up to the module how to
599 * determine that). Has no effect if viewing is not set as a completion condition.
601 * Note that this function must be called before you print the page header because
602 * it is possible that the navigation block may depend on it. If you call it after
603 * printing the header, it shows a developer debug warning.
604 * @uses COMPLETION_VIEW_NOT_REQUIRED
605 * @uses COMPLETION_VIEWED
606 * @uses COMPLETION_COMPLETE
607 * @param object $cm Activity
608 * @param int $userid User ID or 0 (default) for current user
609 * @return void
611 public function set_module_viewed($cm, $userid=0) {
612 global $PAGE, $UNITTEST;
613 if ($PAGE->headerprinted && empty($UNITTEST->running)) {
614 debugging('set_module_viewed must be called before header is printed',
615 DEBUG_DEVELOPER);
618 // Don't do anything if view condition is not turned on
619 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
620 return;
623 // Get current completion state
624 $data = $this->get_data($cm, false, $userid);
626 // If we already viewed it, don't do anything
627 if ($data->viewed == COMPLETION_VIEWED) {
628 return;
631 // OK, change state, save it, and update completion
632 $data->viewed = COMPLETION_VIEWED;
633 $this->internal_set_data($cm, $data);
634 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
638 * Determines how much completion data exists for an activity. This is used when
639 * deciding whether completion information should be 'locked' in the module
640 * editing form.
642 * @global object
643 * @param object $cm Activity
644 * @return int The number of users who have completion data stored for this
645 * activity, 0 if none
647 public function count_user_data($cm) {
648 global $DB;
650 return $DB->get_field_sql("
651 SELECT
652 COUNT(1)
653 FROM
654 {course_modules_completion}
655 WHERE
656 coursemoduleid=? AND completionstate<>0", array($cm->id));
660 * Determines how much course completion data exists for a course. This is used when
661 * deciding whether completion information should be 'locked' in the completion
662 * settings form and activity completion settings.
664 * @global object
665 * @param int $user_id Optionally only get course completion data for a single user
666 * @return int The number of users who have completion data stored for this
667 * course, 0 if none
669 public function count_course_user_data($user_id = null) {
670 global $DB;
672 $sql = '
673 SELECT
674 COUNT(1)
675 FROM
676 {course_completion_crit_compl}
677 WHERE
678 course = ?
681 $params = array($this->course_id);
683 // Limit data to a single user if an ID is supplied
684 if ($user_id) {
685 $sql .= ' AND userid = ?';
686 $params[] = $user_id;
689 return $DB->get_field_sql($sql, $params);
693 * Check if this course's completion criteria should be locked
695 * @return boolean
697 public function is_course_locked() {
698 return (bool) $this->count_course_user_data();
702 * Deletes all course completion completion data.
704 * Intended to be used when unlocking completion criteria settings.
706 * @global object
707 * @return void
709 public function delete_course_completion_data() {
710 global $DB;
712 $DB->delete_records('course_completions', array('course' => $this->course_id));
713 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
717 * Deletes all activity and course completion data for an entire course
718 * (the below delete_all_state function does this for a single activity).
720 * Used by course reset page.
722 public function delete_all_completion_data() {
723 global $DB, $SESSION;
725 // Delete from database.
726 $DB->delete_records_select('course_modules_completion',
727 'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
728 array($this->course_id));
730 // Reset cache for current user.
731 if (isset($SESSION->completioncache) &&
732 array_key_exists($this->course_id, $SESSION->completioncache)) {
734 unset($SESSION->completioncache[$this->course_id]);
737 // Wipe course completion data too.
738 $this->delete_course_completion_data();
742 * Deletes completion state related to an activity for all users.
744 * Intended for use only when the activity itself is deleted.
746 * @global object
747 * @global object
748 * @param object $cm Activity
750 public function delete_all_state($cm) {
751 global $SESSION, $DB;
753 // Delete from database
754 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
756 // Erase cache data for current user if applicable
757 if (isset($SESSION->completioncache) &&
758 array_key_exists($cm->course, $SESSION->completioncache) &&
759 array_key_exists($cm->id, $SESSION->completioncache[$cm->course])) {
761 unset($SESSION->completioncache[$cm->course][$cm->id]);
764 // Check if there is an associated course completion criteria
765 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
766 $acriteria = false;
767 foreach ($criteria as $criterion) {
768 if ($criterion->moduleinstance == $cm->id) {
769 $acriteria = $criterion;
770 break;
774 if ($acriteria) {
775 // Delete all criteria completions relating to this activity
776 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
777 $DB->delete_records('course_completions', array('course' => $this->course_id));
782 * Recalculates completion state related to an activity for all users.
784 * Intended for use if completion conditions change. (This should be avoided
785 * as it may cause some things to become incomplete when they were previously
786 * complete, with the effect - for example - of hiding a later activity that
787 * was previously available.)
789 * Resetting state of manual tickbox has same result as deleting state for
790 * it.
792 * @global object
793 * @uses COMPLETION_TRACKING_MANUAL
794 * @uses COMPLETION_UNKNOWN
795 * @param object $cm Activity
797 public function reset_all_state($cm) {
798 global $DB;
800 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
801 $this->delete_all_state($cm);
802 return;
804 // Get current list of users with completion state
805 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
806 $keepusers = array();
807 foreach ($rs as $rec) {
808 $keepusers[] = $rec->userid;
810 $rs->close();
812 // Delete all existing state [also clears session cache for current user]
813 $this->delete_all_state($cm);
815 // Merge this with list of planned users (according to roles)
816 $trackedusers = $this->get_tracked_users();
817 foreach ($trackedusers as $trackeduser) {
818 $keepusers[] = $trackeduser->id;
820 $keepusers = array_unique($keepusers);
822 // Recalculate state for each kept user
823 foreach ($keepusers as $keepuser) {
824 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
829 * Obtains completion data for a particular activity and user (from the
830 * session cache if available, or by SQL query)
832 * @global object
833 * @global object
834 * @global object
835 * @global object
836 * @uses COMPLETION_CACHE_EXPIRY
837 * @param object $cm Activity; only required field is ->id
838 * @param bool $wholecourse If true (default false) then, when necessary to
839 * fill the cache, retrieves information from the entire course not just for
840 * this one activity
841 * @param int $userid User ID or 0 (default) for current user
842 * @param array $modinfo Supply the value here - this is used for unit
843 * testing and so that it can be called recursively from within
844 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
845 * Otherwise the method calls get_fast_modinfo itself.
846 * @return object Completion data (record from course_modules_completion)
848 public function get_data($cm, $wholecourse=false, $userid=0, $modinfo=null) {
849 global $USER, $CFG, $SESSION, $DB;
851 // Get user ID
852 if (!$userid) {
853 $userid = $USER->id;
856 // Is this the current user?
857 $currentuser = $userid==$USER->id;
859 if ($currentuser && is_object($SESSION)) {
860 // Make sure cache is present and is for current user (loginas
861 // changes this)
862 if (!isset($SESSION->completioncache) || $SESSION->completioncacheuserid!=$USER->id) {
863 $SESSION->completioncache = array();
864 $SESSION->completioncacheuserid = $USER->id;
866 // Expire any old data from cache
867 foreach ($SESSION->completioncache as $courseid=>$activities) {
868 if (empty($activities['updated']) || $activities['updated'] < time()-COMPLETION_CACHE_EXPIRY) {
869 unset($SESSION->completioncache[$courseid]);
872 // See if requested data is present, if so use cache to get it
873 if (isset($SESSION->completioncache) &&
874 array_key_exists($this->course->id, $SESSION->completioncache) &&
875 array_key_exists($cm->id, $SESSION->completioncache[$this->course->id])) {
876 return $SESSION->completioncache[$this->course->id][$cm->id];
880 // Not there, get via SQL
881 if ($currentuser && $wholecourse) {
882 // Get whole course data for cache
883 $alldatabycmc = $DB->get_records_sql("
884 SELECT
885 cmc.*
886 FROM
887 {course_modules} cm
888 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
889 WHERE
890 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
892 // Reindex by cm id
893 $alldata = array();
894 if ($alldatabycmc) {
895 foreach ($alldatabycmc as $data) {
896 $alldata[$data->coursemoduleid] = $data;
900 // Get the module info and build up condition info for each one
901 if (empty($modinfo)) {
902 $modinfo = get_fast_modinfo($this->course, $userid);
904 foreach ($modinfo->cms as $othercm) {
905 if (array_key_exists($othercm->id, $alldata)) {
906 $data = $alldata[$othercm->id];
907 } else {
908 // Row not present counts as 'not complete'
909 $data = new StdClass;
910 $data->id = 0;
911 $data->coursemoduleid = $othercm->id;
912 $data->userid = $userid;
913 $data->completionstate = 0;
914 $data->viewed = 0;
915 $data->timemodified = 0;
917 $SESSION->completioncache[$this->course->id][$othercm->id] = $data;
919 $SESSION->completioncache[$this->course->id]['updated'] = time();
921 if (!isset($SESSION->completioncache[$this->course->id][$cm->id])) {
922 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
924 return $SESSION->completioncache[$this->course->id][$cm->id];
926 } else {
927 // Get single record
928 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
929 if ($data == false) {
930 // Row not present counts as 'not complete'
931 $data = new StdClass;
932 $data->id = 0;
933 $data->coursemoduleid = $cm->id;
934 $data->userid = $userid;
935 $data->completionstate = 0;
936 $data->viewed = 0;
937 $data->timemodified = 0;
940 // Put in cache
941 if ($currentuser) {
942 $SESSION->completioncache[$this->course->id][$cm->id] = $data;
943 // For single updates, only set date if it was empty before
944 if (empty($SESSION->completioncache[$this->course->id]['updated'])) {
945 $SESSION->completioncache[$this->course->id]['updated'] = time();
950 return $data;
954 * Updates completion data for a particular coursemodule and user (user is
955 * determined from $data).
957 * (Internal function. Not private, so we can unit-test it.)
959 * @global object
960 * @global object
961 * @global object
962 * @param object $cm Activity
963 * @param object $data Data about completion for that user
965 function internal_set_data($cm, $data) {
966 global $USER, $SESSION, $DB;
968 $transaction = $DB->start_delegated_transaction();
969 if (!$data->id) {
970 // Check there isn't really a row
971 $data->id = $DB->get_field('course_modules_completion', 'id',
972 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
974 if (!$data->id) {
975 // Didn't exist before, needs creating
976 $data->id = $DB->insert_record('course_modules_completion', $data);
977 } else {
978 // Has real (nonzero) id meaning that a database row exists, update
979 $DB->update_record('course_modules_completion', $data);
981 $transaction->allow_commit();
983 if ($data->userid == $USER->id) {
984 $SESSION->completioncache[$cm->course][$cm->id] = $data;
985 $reset = 'reset';
986 get_fast_modinfo($reset);
991 * Obtains a list of activities for which completion is enabled on the
992 * course. The list is ordered by the section order of those activities.
994 * @global object
995 * @uses COMPLETION_TRACKING_NONE
996 * @param array $modinfo For unit testing only, supply the value
997 * here. Otherwise the method calls get_fast_modinfo
998 * @return array Array from $cmid => $cm of all activities with completion enabled,
999 * empty array if none
1001 public function get_activities($modinfo=null) {
1002 global $DB;
1004 // Obtain those activities which have completion turned on
1005 $withcompletion = $DB->get_records_select('course_modules', 'course='.$this->course->id.
1006 ' AND completion<>'.COMPLETION_TRACKING_NONE);
1007 if (!$withcompletion) {
1008 return array();
1011 // Use modinfo to get section order and also add in names
1012 if (empty($modinfo)) {
1013 $modinfo = get_fast_modinfo($this->course);
1015 $result = array();
1016 foreach ($modinfo->sections as $sectioncms) {
1017 foreach ($sectioncms as $cmid) {
1018 if (array_key_exists($cmid, $withcompletion)) {
1019 $result[$cmid] = $withcompletion[$cmid];
1020 $result[$cmid]->modname = $modinfo->cms[$cmid]->modname;
1021 $result[$cmid]->name = $modinfo->cms[$cmid]->name;
1026 return $result;
1031 * Checks to see if the userid supplied has a tracked role in
1032 * this course
1034 * @param $userid User id
1035 * @return bool
1037 function is_tracked_user($userid) {
1038 global $DB;
1040 $tracked = $this->generate_tracked_user_sql();
1042 $sql = "SELECT u.id ";
1043 $sql .= $tracked->sql;
1044 $sql .= ' AND u.id = :userid';
1046 $params = $tracked->data;
1047 $params['userid'] = (int)$userid;
1048 return $DB->record_exists_sql($sql, $params);
1053 * Return number of users whose progress is tracked in this course
1055 * Optionally supply a search's where clause, or a group id
1057 * @param string $where Where clause sql
1058 * @param array $where_params Where clause params
1059 * @param int $groupid Group id
1060 * @return int
1062 function get_num_tracked_users($where = '', $where_params = array(), $groupid = 0) {
1063 global $DB;
1065 $tracked = $this->generate_tracked_user_sql($groupid);
1067 $sql = "SELECT COUNT(u.id) ";
1068 $sql .= $tracked->sql;
1070 if ($where) {
1071 $sql .= " AND $where";
1074 $params = array_merge($tracked->data, $where_params);
1075 return $DB->count_records_sql($sql, $params);
1080 * Return array of users whose progress is tracked in this course
1082 * Optionally supply a search's where caluse, group id, sorting, paging
1084 * @param string $where Where clause sql (optional)
1085 * @param array $where_params Where clause params (optional)
1086 * @param integer $groupid Group ID to restrict to (optional)
1087 * @param string $sort Order by clause (optional)
1088 * @param integer $limitfrom Result start (optional)
1089 * @param integer $limitnum Result max size (optional)
1090 * @param context $extracontext If set, includes extra user information fields
1091 * as appropriate to display for current user in this context
1092 * @return array
1094 function get_tracked_users($where = '', $where_params = array(), $groupid = 0,
1095 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1097 global $DB;
1099 $tracked = $this->generate_tracked_user_sql($groupid);
1100 $params = $tracked->data;
1102 $sql = "
1103 SELECT
1104 u.id,
1105 u.firstname,
1106 u.lastname,
1107 u.idnumber
1109 if ($extracontext) {
1110 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1113 $sql .= $tracked->sql;
1115 if ($where) {
1116 $sql .= " AND $where";
1117 $params = array_merge($params, $where_params);
1120 if ($sort) {
1121 $sql .= " ORDER BY $sort";
1124 $users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1125 return $users ? $users : array(); // In case it returns false
1130 * Generate the SQL for finding tracked users in this course
1132 * Returns an object containing the sql fragment and an array of
1133 * bound data params.
1135 * @param integer $groupid
1136 * @return object
1138 function generate_tracked_user_sql($groupid = 0) {
1139 global $CFG;
1141 $return = new stdClass();
1142 $return->sql = '';
1143 $return->data = array();
1145 if (!empty($CFG->gradebookroles)) {
1146 $roles = ' AND ra.roleid IN ('.$CFG->gradebookroles.')';
1147 } else {
1148 // This causes it to default to everyone (if there is no student role)
1149 $roles = '';
1152 // Build context sql
1153 $context = get_context_instance(CONTEXT_COURSE, $this->course->id);
1154 $parentcontexts = substr($context->path, 1); // kill leading slash
1155 $parentcontexts = str_replace('/', ',', $parentcontexts);
1156 if ($parentcontexts !== '') {
1157 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
1160 $groupjoin = '';
1161 $groupselect = '';
1162 if ($groupid) {
1163 $groupjoin = "JOIN {groups_members} gm
1164 ON gm.userid = u.id";
1165 $groupselect = " AND gm.groupid = :groupid ";
1167 $return->data['groupid'] = $groupid;
1170 $return->sql = "
1171 FROM
1172 {user} u
1173 INNER JOIN
1174 {role_assignments} ra
1175 ON ra.userid = u.id
1176 INNER JOIN
1177 {role} r
1178 ON r.id = ra.roleid
1179 INNER JOIN
1180 {user_enrolments} ue
1181 ON ue.userid = u.id
1182 INNER JOIN
1183 {enrol} e
1184 ON e.id = ue.enrolid
1185 INNER JOIN
1186 {course} c
1187 ON c.id = e.courseid
1188 $groupjoin
1189 WHERE
1190 (ra.contextid = :contextid $parentcontexts)
1191 AND c.id = :courseid
1192 AND ue.status = 0
1193 AND e.status = 0
1194 AND ue.timestart < :now1
1195 AND (ue.timeend > :now2 OR ue.timeend = 0)
1196 $groupselect
1197 $roles
1200 $now = time();
1201 $return->data['now1'] = $now;
1202 $return->data['now2'] = $now;
1203 $return->data['contextid'] = $context->id;
1204 $return->data['courseid'] = $this->course->id;
1206 return $return;
1210 * Obtains progress information across a course for all users on that course, or
1211 * for all users in a specific group. Intended for use when displaying progress.
1213 * This includes only users who, in course context, have one of the roles for
1214 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1216 * Users are included (in the first array) even if they do not have
1217 * completion progress for any course-module.
1219 * @global object
1220 * @global object
1221 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1222 * last name
1223 * @param string $where Where clause sql (optional)
1224 * @param array $where_params Where clause params (optional)
1225 * @param int $groupid Group ID or 0 (default)/false for all groups
1226 * @param int $pagesize Number of users to actually return (optional)
1227 * @param int $start User to start at if paging (optional)
1228 * @param context $extracontext If set, includes extra user information fields
1229 * as appropriate to display for current user in this context
1230 * @return Object with ->total and ->start (same as $start) and ->users;
1231 * an array of user objects (like mdl_user id, firstname, lastname)
1232 * containing an additional ->progress array of coursemoduleid => completionstate
1234 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1235 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1236 global $CFG, $DB;
1238 // Get list of applicable users
1239 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1240 $start, $pagesize, $extracontext);
1242 // Get progress information for these users in groups of 1, 000 (if needed)
1243 // to avoid making the SQL IN too long
1244 $results = array();
1245 $userids = array();
1246 foreach ($users as $user) {
1247 $userids[] = $user->id;
1248 $results[$user->id] = $user;
1249 $results[$user->id]->progress = array();
1252 for($i=0; $i<count($userids); $i+=1000) {
1253 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1255 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1256 array_splice($params, 0, 0, array($this->course->id));
1257 $rs = $DB->get_recordset_sql("
1258 SELECT
1259 cmc.*
1260 FROM
1261 {course_modules} cm
1262 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1263 WHERE
1264 cm.course=? AND cmc.userid $insql
1265 ", $params);
1266 foreach ($rs as $progress) {
1267 $progress = (object)$progress;
1268 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1270 $rs->close();
1273 return $results;
1277 * Called by grade code to inform the completion system when a grade has
1278 * been changed. If the changed grade is used to determine completion for
1279 * the course-module, then the completion status will be updated.
1281 * @uses COMPLETION_TRACKING_MANUAL
1282 * @uses COMPLETION_INCOMPLETE
1283 * @param object $cm Course-module for item that owns grade
1284 * @param grade_item $item Grade item
1285 * @param object $grade
1286 * @param bool $deleted
1287 * @return void
1289 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1290 // Bail out now if completion is not enabled for course-module, it is enabled
1291 // but is set to manual, grade is not used to compute completion, or this
1292 // is a different numbered grade
1293 if (!$this->is_enabled($cm) ||
1294 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1295 is_null($cm->completiongradeitemnumber) ||
1296 $item->itemnumber != $cm->completiongradeitemnumber) {
1297 return;
1300 // What is the expected result based on this grade?
1301 if ($deleted) {
1302 // Grade being deleted, so only change could be to make it incomplete
1303 $possibleresult = COMPLETION_INCOMPLETE;
1304 } else {
1305 $possibleresult = $this->internal_get_grade_state($item, $grade);
1308 // OK, let's update state based on this
1309 $this->update_state($cm, $possibleresult, $grade->userid);
1313 * Calculates the completion state that would result from a graded item
1314 * (where grade-based completion is turned on) based on the actual grade
1315 * and settings.
1317 * Internal function. Not private, so we can unit-test it.
1319 * @uses COMPLETION_INCOMPLETE
1320 * @uses COMPLETION_COMPLETE_PASS
1321 * @uses COMPLETION_COMPLETE_FAIL
1322 * @uses COMPLETION_COMPLETE
1323 * @param object $item grade_item
1324 * @param object $grade grade_grade
1325 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1327 function internal_get_grade_state($item, $grade) {
1328 if (!$grade) {
1329 return COMPLETION_INCOMPLETE;
1331 // Conditions to show pass/fail:
1332 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1333 // b) Grade is visible (neither hidden nor hidden-until)
1334 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1335 // Use final grade if set otherwise raw grade
1336 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1338 // We are displaying and tracking pass/fail
1339 if ($score >= $item->gradepass) {
1340 return COMPLETION_COMPLETE_PASS;
1341 } else {
1342 return COMPLETION_COMPLETE_FAIL;
1344 } else {
1345 // Not displaying pass/fail, so just if there is a grade
1346 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1347 // Grade exists, so maybe complete now
1348 return COMPLETION_COMPLETE;
1349 } else {
1350 // Grade does not exist, so maybe incomplete now
1351 return COMPLETION_INCOMPLETE;
1357 * This is to be used only for system errors (things that shouldn't happen)
1358 * and not user-level errors.
1360 * @global object
1361 * @param string $error Error string (will not be displayed to user unless
1362 * debugging is enabled)
1363 * @return void Throws moodle_exception Exception with the error string as debug info
1365 function internal_systemerror($error) {
1366 global $CFG;
1367 throw new moodle_exception('err_system','completion',
1368 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1372 * For testing only. Wipes information cached in user session.
1374 * @global object
1376 static function wipe_session_cache() {
1377 global $SESSION;
1378 unset($SESSION->completioncache);
1379 unset($SESSION->completioncacheuserid);