MDL-32843 import YUI 3.5.1
[moodle.git] / lib / completionlib.php
bloba47a1f89ee294268994ba03ca8393f86548cd030
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->libdir.'/completion/completion_aggregation.php';
35 require_once $CFG->libdir.'/completion/completion_criteria.php';
36 require_once $CFG->libdir.'/completion/completion_completion.php';
37 require_once $CFG->libdir.'/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 * Class represents completion information for a course.
152 * Does not contain any data, so you can safely construct it multiple times
153 * without causing any problems.
155 * @package core
156 * @category completion
157 * @copyright 2008 Sam Marshall
158 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
160 class completion_info {
162 /* @var stdClass Course object passed during construction */
163 private $course;
165 /* @var int Course id */
166 public $course_id;
168 /* @var array Completion criteria {@link completion_info::get_criteria()} */
169 private $criteria;
172 * Return array of aggregation methods
173 * @return array
175 public static function get_aggregation_methods() {
176 return array(
177 COMPLETION_AGGREGATION_ALL => get_string('all'),
178 COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
183 * Constructs with course details.
185 * When instantiating a new completion info object you must provide a course
186 * object with at least id, and enablecompletion properties.
188 * @param stdClass $course Moodle course object.
190 public function __construct($course) {
191 $this->course = $course;
192 $this->course_id = $course->id;
196 * Determines whether completion is enabled across entire site.
198 * @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
199 * COMPLETION_DISABLED (false) if it's complete
201 public static function is_enabled_for_site() {
202 global $CFG;
203 return !empty($CFG->enablecompletion);
207 * Checks whether completion is enabled in a particular course and possibly
208 * activity.
210 * @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
211 * completion enable state.
212 * @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
213 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
214 * for a course-module.
216 public function is_enabled($cm = null) {
217 global $CFG, $DB;
219 // First check global completion
220 if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
221 return COMPLETION_DISABLED;
224 // Load data if we do not have enough
225 if (!isset($this->course->enablecompletion)) {
226 $this->course->enablecompletion = $DB->get_field('course', 'enablecompletion', array('id' => $this->course->id));
229 // Check course completion
230 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
231 return COMPLETION_DISABLED;
234 // If there was no $cm and we got this far, then it's enabled
235 if (!$cm) {
236 return COMPLETION_ENABLED;
239 // Return course-module completion value
240 return $cm->completion;
244 * Displays the 'Your progress' help icon, if completion tracking is enabled.
245 * Just prints the result of display_help_icon().
247 * @deprecated since Moodle 2.0 - Use display_help_icon instead.
249 public function print_help_icon() {
250 print $this->display_help_icon();
254 * Returns the 'Your progress' help icon, if completion tracking is enabled.
256 * @return string HTML code for help icon, or blank if not needed
258 public function display_help_icon() {
259 global $PAGE, $OUTPUT;
260 $result = '';
261 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
262 $result .= '<span id = "completionprogressid" class="completionprogress">'.get_string('yourprogress','completion').' ';
263 $result .= $OUTPUT->help_icon('completionicons', 'completion');
264 $result .= '</span>';
266 return $result;
270 * Get a course completion for a user
272 * @param int $user_id User id
273 * @param int $criteriatype Specific criteria type to return
274 * @return bool|completion_criteria_completion returns false on fail
276 public function get_completion($user_id, $criteriatype) {
277 $completions = $this->get_completions($user_id, $criteriatype);
279 if (empty($completions)) {
280 return false;
281 } elseif (count($completions) > 1) {
282 print_error('multipleselfcompletioncriteria', 'completion');
285 return $completions[0];
289 * Get all course criteria's completion objects for a user
291 * @param int $user_id User id
292 * @param int $criteriatype Specific criteria type to return (optional)
293 * @return array
295 public function get_completions($user_id, $criteriatype = null) {
296 $criterion = $this->get_criteria($criteriatype);
298 $completions = array();
300 foreach ($criterion as $criteria) {
301 $params = array(
302 'course' => $this->course_id,
303 'userid' => $user_id,
304 'criteriaid' => $criteria->id
307 $completion = new completion_criteria_completion($params);
308 $completion->attach_criteria($criteria);
310 $completions[] = $completion;
313 return $completions;
317 * Get completion object for a user and a criteria
319 * @param int $user_id User id
320 * @param completion_criteria $criteria Criteria object
321 * @return completion_criteria_completion
323 public function get_user_completion($user_id, $criteria) {
324 $params = array(
325 'criteriaid' => $criteria->id,
326 'userid' => $user_id
329 $completion = new completion_criteria_completion($params);
330 return $completion;
334 * Check if course has completion criteria set
336 * @return bool Returns true if there are criteria
338 public function has_criteria() {
339 $criteria = $this->get_criteria();
341 return (bool) count($criteria);
345 * Get course completion criteria
347 * @param int $criteriatype Specific criteria type to return (optional)
349 public function get_criteria($criteriatype = null) {
351 // Fill cache if empty
352 if (!is_array($this->criteria)) {
353 global $DB;
355 $params = array(
356 'course' => $this->course->id
359 // Load criteria from database
360 $records = (array)$DB->get_records('course_completion_criteria', $params);
362 // Build array of criteria objects
363 $this->criteria = array();
364 foreach ($records as $record) {
365 $this->criteria[$record->id] = completion_criteria::factory($record);
369 // If after all criteria
370 if ($criteriatype === null) {
371 return $this->criteria;
374 // If we are only after a specific criteria type
375 $criteria = array();
376 foreach ($this->criteria as $criterion) {
378 if ($criterion->criteriatype != $criteriatype) {
379 continue;
382 $criteria[$criterion->id] = $criterion;
385 return $criteria;
389 * Get aggregation method
391 * @param int $criteriatype If none supplied, get overall aggregation method (optional)
392 * @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
394 public function get_aggregation_method($criteriatype = null) {
395 $params = array(
396 'course' => $this->course_id,
397 'criteriatype' => $criteriatype
400 $aggregation = new completion_aggregation($params);
402 if (!$aggregation->id) {
403 $aggregation->method = COMPLETION_AGGREGATION_ALL;
406 return $aggregation->method;
410 * Get incomplete course completion criteria
412 * @return array
414 public function get_incomplete_criteria() {
415 $incomplete = array();
417 foreach ($this->get_criteria() as $criteria) {
418 if (!$criteria->is_complete()) {
419 $incomplete[] = $criteria;
423 return $incomplete;
427 * Clear old course completion criteria
429 public function clear_criteria() {
430 global $DB;
431 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id));
432 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
434 $this->delete_course_completion_data();
438 * Has the supplied user completed this course
440 * @param int $user_id User's id
441 * @return boolean
443 public function is_course_complete($user_id) {
444 $params = array(
445 'userid' => $user_id,
446 'course' => $this->course_id
449 $ccompletion = new completion_completion($params);
450 return $ccompletion->is_complete();
454 * Updates (if necessary) the completion state of activity $cm for the given
455 * user.
457 * For manual completion, this function is called when completion is toggled
458 * with $possibleresult set to the target state.
460 * For automatic completion, this function should be called every time a module
461 * does something which might influence a user's completion state. For example,
462 * if a forum provides options for marking itself 'completed' once a user makes
463 * N posts, this function should be called every time a user makes a new post.
464 * [After the post has been saved to the database]. When calling, you do not
465 * need to pass in the new completion state. Instead this function carries out
466 * completion calculation by checking grades and viewed state itself, and
467 * calling the involved module via modulename_get_completion_state() to check
468 * module-specific conditions.
470 * @param stdClass|cm_info $cm Course-module
471 * @param int $possibleresult Expected completion result. If the event that
472 * has just occurred (e.g. add post) can only result in making the activity
473 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
474 * has just occurred (e.g. delete post) can only result in making the activity
475 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
476 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
477 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
478 * processing early if the user's completion state already matches the expected
479 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
480 * must be used; these directly set the specified state.
481 * @param int $userid User ID to be updated. Default 0 = current user
482 * @return void
484 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
485 global $USER, $SESSION;
487 // Do nothing if completion is not enabled for that activity
488 if (!$this->is_enabled($cm)) {
489 return;
492 // Get current value of completion state and do nothing if it's same as
493 // the possible result of this change. If the change is to COMPLETE and the
494 // current value is one of the COMPLETE_xx subtypes, ignore that as well
495 $current = $this->get_data($cm, false, $userid);
496 if ($possibleresult == $current->completionstate ||
497 ($possibleresult == COMPLETION_COMPLETE &&
498 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
499 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
500 return;
503 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
504 // For manual tracking we set the result directly
505 switch($possibleresult) {
506 case COMPLETION_COMPLETE:
507 case COMPLETION_INCOMPLETE:
508 $newstate = $possibleresult;
509 break;
510 default:
511 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
514 } else {
515 // Automatic tracking; get new state
516 $newstate = $this->internal_get_state($cm, $userid, $current);
519 // If changed, update
520 if ($newstate != $current->completionstate) {
521 $current->completionstate = $newstate;
522 $current->timemodified = time();
523 $this->internal_set_data($cm, $current);
528 * Calculates the completion state for an activity and user.
530 * Internal function. Not private, so we can unit-test it.
532 * @param stdClass|cm_info $cm Activity
533 * @param int $userid ID of user
534 * @param stdClass $current Previous completion information from database
535 * @return mixed
537 public function internal_get_state($cm, $userid, $current) {
538 global $USER, $DB, $CFG;
540 // Get user ID
541 if (!$userid) {
542 $userid = $USER->id;
545 // Check viewed
546 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
547 $current->viewed == COMPLETION_NOT_VIEWED) {
549 return COMPLETION_INCOMPLETE;
552 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
553 if (!isset($cm->modname)) {
554 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
557 $newstate = COMPLETION_COMPLETE;
559 // Check grade
560 if (!is_null($cm->completiongradeitemnumber)) {
561 require_once($CFG->libdir.'/gradelib.php');
562 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
563 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
564 'itemnumber'=>$cm->completiongradeitemnumber));
565 if ($item) {
566 // Fetch 'grades' (will be one or none)
567 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
568 if (empty($grades)) {
569 // No grade for user
570 return COMPLETION_INCOMPLETE;
572 if (count($grades) > 1) {
573 $this->internal_systemerror("Unexpected result: multiple grades for
574 item '{$item->id}', user '{$userid}'");
576 $newstate = self::internal_get_grade_state($item, reset($grades));
577 if ($newstate == COMPLETION_INCOMPLETE) {
578 return COMPLETION_INCOMPLETE;
581 } else {
582 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
583 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
587 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
588 $function = $cm->modname.'_get_completion_state';
589 if (!function_exists($function)) {
590 $this->internal_systemerror("Module {$cm->modname} claims to support
591 FEATURE_COMPLETION_HAS_RULES but does not have required
592 {$cm->modname}_get_completion_state function");
594 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
595 return COMPLETION_INCOMPLETE;
599 return $newstate;
604 * Marks a module as viewed.
606 * Should be called whenever a module is 'viewed' (it is up to the module how to
607 * determine that). Has no effect if viewing is not set as a completion condition.
609 * Note that this function must be called before you print the page header because
610 * it is possible that the navigation block may depend on it. If you call it after
611 * printing the header, it shows a developer debug warning.
613 * @param stdClass|cm_info $cm Activity
614 * @param int $userid User ID or 0 (default) for current user
615 * @return void
617 public function set_module_viewed($cm, $userid=0) {
618 global $PAGE, $UNITTEST;
619 if ($PAGE->headerprinted && empty($UNITTEST->running)) {
620 debugging('set_module_viewed must be called before header is printed',
621 DEBUG_DEVELOPER);
623 // Don't do anything if view condition is not turned on
624 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
625 return;
627 // Get current completion state
628 $data = $this->get_data($cm, $userid);
629 // If we already viewed it, don't do anything
630 if ($data->viewed == COMPLETION_VIEWED) {
631 return;
633 // OK, change state, save it, and update completion
634 $data->viewed = COMPLETION_VIEWED;
635 $this->internal_set_data($cm, $data);
636 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
640 * Determines how much completion data exists for an activity. This is used when
641 * deciding whether completion information should be 'locked' in the module
642 * editing form.
644 * @param cm_info $cm Activity
645 * @return int The number of users who have completion data stored for this
646 * activity, 0 if none
648 public function count_user_data($cm) {
649 global $DB;
651 return $DB->get_field_sql("
652 SELECT
653 COUNT(1)
654 FROM
655 {course_modules_completion}
656 WHERE
657 coursemoduleid=? AND completionstate<>0", array($cm->id));
661 * Determines how much course completion data exists for a course. This is used when
662 * deciding whether completion information should be 'locked' in the completion
663 * settings form and activity completion settings.
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 public function delete_course_completion_data() {
707 global $DB;
709 $DB->delete_records('course_completions', array('course' => $this->course_id));
710 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
714 * Deletes completion state related to an activity for all users.
716 * Intended for use only when the activity itself is deleted.
718 * @param stdClass|cm_info $cm Activity
720 public function delete_all_state($cm) {
721 global $SESSION, $DB;
723 // Delete from database
724 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
726 // Erase cache data for current user if applicable
727 if (isset($SESSION->completioncache) &&
728 array_key_exists($cm->course, $SESSION->completioncache) &&
729 array_key_exists($cm->id, $SESSION->completioncache[$cm->course])) {
731 unset($SESSION->completioncache[$cm->course][$cm->id]);
734 // Check if there is an associated course completion criteria
735 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
736 $acriteria = false;
737 foreach ($criteria as $criterion) {
738 if ($criterion->moduleinstance == $cm->id) {
739 $acriteria = $criterion;
740 break;
744 if ($acriteria) {
745 // Delete all criteria completions relating to this activity
746 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
747 $DB->delete_records('course_completions', array('course' => $this->course_id));
752 * Recalculates completion state related to an activity for all users.
754 * Intended for use if completion conditions change. (This should be avoided
755 * as it may cause some things to become incomplete when they were previously
756 * complete, with the effect - for example - of hiding a later activity that
757 * was previously available.)
759 * Resetting state of manual tickbox has same result as deleting state for
760 * it.
762 * @param stcClass|cm_info $cm Activity
764 public function reset_all_state($cm) {
765 global $DB;
767 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
768 $this->delete_all_state($cm);
769 return;
771 // Get current list of users with completion state
772 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
773 $keepusers = array();
774 foreach ($rs as $rec) {
775 $keepusers[] = $rec->userid;
777 $rs->close();
779 // Delete all existing state [also clears session cache for current user]
780 $this->delete_all_state($cm);
782 // Merge this with list of planned users (according to roles)
783 $trackedusers = $this->get_tracked_users();
784 foreach ($trackedusers as $trackeduser) {
785 $keepusers[] = $trackeduser->id;
787 $keepusers = array_unique($keepusers);
789 // Recalculate state for each kept user
790 foreach ($keepusers as $keepuser) {
791 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
796 * Obtains completion data for a particular activity and user (from the
797 * session cache if available, or by SQL query)
799 * @param stcClass|cm_info $cm Activity; only required field is ->id
800 * @param bool $wholecourse If true (default false) then, when necessary to
801 * fill the cache, retrieves information from the entire course not just for
802 * this one activity
803 * @param int $userid User ID or 0 (default) for current user
804 * @param array $modinfo Supply the value here - this is used for unit
805 * testing and so that it can be called recursively from within
806 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
807 * Otherwise the method calls get_fast_modinfo itself.
808 * @return object Completion data (record from course_modules_completion)
810 public function get_data($cm, $wholecourse = false, $userid = 0, $modinfo = null) {
811 global $USER, $CFG, $SESSION, $DB;
813 // Get user ID
814 if (!$userid) {
815 $userid = $USER->id;
818 // Is this the current user?
819 $currentuser = $userid==$USER->id;
821 if ($currentuser && is_object($SESSION)) {
822 // Make sure cache is present and is for current user (loginas
823 // changes this)
824 if (!isset($SESSION->completioncache) || $SESSION->completioncacheuserid!=$USER->id) {
825 $SESSION->completioncache = array();
826 $SESSION->completioncacheuserid = $USER->id;
828 // Expire any old data from cache
829 foreach ($SESSION->completioncache as $courseid=>$activities) {
830 if (empty($activities['updated']) || $activities['updated'] < time()-COMPLETION_CACHE_EXPIRY) {
831 unset($SESSION->completioncache[$courseid]);
834 // See if requested data is present, if so use cache to get it
835 if (isset($SESSION->completioncache) &&
836 array_key_exists($this->course->id, $SESSION->completioncache) &&
837 array_key_exists($cm->id, $SESSION->completioncache[$this->course->id])) {
838 return $SESSION->completioncache[$this->course->id][$cm->id];
842 // Not there, get via SQL
843 if ($currentuser && $wholecourse) {
844 // Get whole course data for cache
845 $alldatabycmc = $DB->get_records_sql("
846 SELECT
847 cmc.*
848 FROM
849 {course_modules} cm
850 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
851 WHERE
852 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
854 // Reindex by cm id
855 $alldata = array();
856 if ($alldatabycmc) {
857 foreach ($alldatabycmc as $data) {
858 $alldata[$data->coursemoduleid] = $data;
862 // Get the module info and build up condition info for each one
863 if (empty($modinfo)) {
864 $modinfo = get_fast_modinfo($this->course, $userid);
866 foreach ($modinfo->cms as $othercm) {
867 if (array_key_exists($othercm->id, $alldata)) {
868 $data = $alldata[$othercm->id];
869 } else {
870 // Row not present counts as 'not complete'
871 $data = new StdClass;
872 $data->id = 0;
873 $data->coursemoduleid = $othercm->id;
874 $data->userid = $userid;
875 $data->completionstate = 0;
876 $data->viewed = 0;
877 $data->timemodified = 0;
879 $SESSION->completioncache[$this->course->id][$othercm->id] = $data;
881 $SESSION->completioncache[$this->course->id]['updated'] = time();
883 if (!isset($SESSION->completioncache[$this->course->id][$cm->id])) {
884 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
886 return $SESSION->completioncache[$this->course->id][$cm->id];
888 } else {
889 // Get single record
890 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
891 if ($data == false) {
892 // Row not present counts as 'not complete'
893 $data = new StdClass;
894 $data->id = 0;
895 $data->coursemoduleid = $cm->id;
896 $data->userid = $userid;
897 $data->completionstate = 0;
898 $data->viewed = 0;
899 $data->timemodified = 0;
902 // Put in cache
903 if ($currentuser) {
904 $SESSION->completioncache[$this->course->id][$cm->id] = $data;
905 // For single updates, only set date if it was empty before
906 if (empty($SESSION->completioncache[$this->course->id]['updated'])) {
907 $SESSION->completioncache[$this->course->id]['updated'] = time();
912 return $data;
916 * Updates completion data for a particular coursemodule and user (user is
917 * determined from $data).
919 * (Internal function. Not private, so we can unit-test it.)
921 * @param stdClass|cm_info $cm Activity
922 * @param stdClass $data Data about completion for that user
924 public function internal_set_data($cm, $data) {
925 global $USER, $SESSION, $DB;
927 $transaction = $DB->start_delegated_transaction();
928 if (!$data->id) {
929 // Check there isn't really a row
930 $data->id = $DB->get_field('course_modules_completion', 'id',
931 array('coursemoduleid'=>$data->coursemoduleid, 'userid'=>$data->userid));
933 if (!$data->id) {
934 // Didn't exist before, needs creating
935 $data->id = $DB->insert_record('course_modules_completion', $data);
936 } else {
937 // Has real (nonzero) id meaning that a database row exists, update
938 $DB->update_record('course_modules_completion', $data);
940 $transaction->allow_commit();
942 if ($data->userid == $USER->id) {
943 $SESSION->completioncache[$cm->course][$cm->id] = $data;
944 $reset = 'reset';
945 get_fast_modinfo($reset);
950 * Obtains a list of activities for which completion is enabled on the
951 * course. The list is ordered by the section order of those activities.
953 * @param array $modinfo For unit testing only, supply the value
954 * here. Otherwise the method calls get_fast_modinfo
955 * @return array Array from $cmid => $cm of all activities with completion enabled,
956 * empty array if none
958 public function get_activities($modinfo=null) {
959 global $DB;
961 // Obtain those activities which have completion turned on
962 $withcompletion = $DB->get_records_select('course_modules', 'course='.$this->course->id.
963 ' AND completion<>'.COMPLETION_TRACKING_NONE);
964 if (!$withcompletion) {
965 return array();
968 // Use modinfo to get section order and also add in names
969 if (empty($modinfo)) {
970 $modinfo = get_fast_modinfo($this->course);
972 $result = array();
973 foreach ($modinfo->sections as $sectioncms) {
974 foreach ($sectioncms as $cmid) {
975 if (array_key_exists($cmid, $withcompletion)) {
976 $result[$cmid] = $withcompletion[$cmid];
977 $result[$cmid]->modname = $modinfo->cms[$cmid]->modname;
978 $result[$cmid]->name = $modinfo->cms[$cmid]->name;
983 return $result;
987 * Checks to see if the userid supplied has a tracked role in
988 * this course
990 * @param int $userid User id
991 * @return bool
993 public function is_tracked_user($userid) {
994 global $DB;
996 $tracked = $this->generate_tracked_user_sql();
998 $sql = "SELECT u.id ";
999 $sql .= $tracked->sql;
1000 $sql .= ' AND u.id = :userid';
1002 $params = $tracked->data;
1003 $params['userid'] = (int)$userid;
1004 return $DB->record_exists_sql($sql, $params);
1008 * Return number of users whose progress is tracked in this course
1010 * Optionally supply a search's where clause, or a group id
1012 * @param string $where Where clause sql
1013 * @param array $where_params Where clause params
1014 * @param int $groupid Group id
1015 * @return int
1017 public function get_num_tracked_users($where = '', $where_params = array(), $groupid = 0) {
1018 global $DB;
1020 $tracked = $this->generate_tracked_user_sql($groupid);
1022 $sql = "SELECT COUNT(u.id) ";
1023 $sql .= $tracked->sql;
1025 if ($where) {
1026 $sql .= " AND $where";
1029 $params = array_merge($tracked->data, $where_params);
1030 return $DB->count_records_sql($sql, $params);
1034 * Return array of users whose progress is tracked in this course
1036 * Optionally supply a search's where caluse, group id, sorting, paging
1038 * @param string $where Where clause sql (optional)
1039 * @param array $where_params Where clause params (optional)
1040 * @param integer $groupid Group ID to restrict to (optional)
1041 * @param string $sort Order by clause (optional)
1042 * @param integer $limitfrom Result start (optional)
1043 * @param integer $limitnum Result max size (optional)
1044 * @param context $extracontext If set, includes extra user information fields
1045 * as appropriate to display for current user in this context
1046 * @return array
1048 public function get_tracked_users($where = '', $where_params = array(), $groupid = 0,
1049 $sort = '', $limitfrom = '', $limitnum = '', context $extracontext = null) {
1051 global $DB;
1053 $tracked = $this->generate_tracked_user_sql($groupid);
1054 $params = $tracked->data;
1056 $sql = "
1057 SELECT
1058 u.id,
1059 u.firstname,
1060 u.lastname,
1061 u.idnumber
1063 if ($extracontext) {
1064 $sql .= get_extra_user_fields_sql($extracontext, 'u', '', array('idnumber'));
1067 $sql .= $tracked->sql;
1069 if ($where) {
1070 $sql .= " AND $where";
1071 $params = array_merge($params, $where_params);
1074 if ($sort) {
1075 $sql .= " ORDER BY $sort";
1078 $users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1079 return $users ? $users : array(); // In case it returns false
1083 * Generate the SQL for finding tracked users in this course
1085 * Returns an object containing the sql fragment and an array of
1086 * bound data params.
1088 * @param integer $groupid
1089 * @return stdClass With two properties, sql (string), and data (array)
1091 public function generate_tracked_user_sql($groupid = 0) {
1092 global $CFG;
1094 $return = new stdClass();
1095 $return->sql = '';
1096 $return->data = array();
1098 if (!empty($CFG->gradebookroles)) {
1099 $roles = ' AND ra.roleid IN ('.$CFG->gradebookroles.')';
1100 } else {
1101 // This causes it to default to everyone (if there is no student role)
1102 $roles = '';
1105 // Build context sql
1106 $context = get_context_instance(CONTEXT_COURSE, $this->course->id);
1107 $parentcontexts = substr($context->path, 1); // kill leading slash
1108 $parentcontexts = str_replace('/', ',', $parentcontexts);
1109 if ($parentcontexts !== '') {
1110 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
1113 $groupjoin = '';
1114 $groupselect = '';
1115 if ($groupid) {
1116 $groupjoin = "JOIN {groups_members} gm
1117 ON gm.userid = u.id";
1118 $groupselect = " AND gm.groupid = :groupid ";
1120 $return->data['groupid'] = $groupid;
1123 $return->sql = "
1124 FROM
1125 {user} u
1126 INNER JOIN
1127 {role_assignments} ra
1128 ON ra.userid = u.id
1129 INNER JOIN
1130 {role} r
1131 ON r.id = ra.roleid
1132 INNER JOIN
1133 {user_enrolments} ue
1134 ON ue.userid = u.id
1135 INNER JOIN
1136 {enrol} e
1137 ON e.id = ue.enrolid
1138 INNER JOIN
1139 {course} c
1140 ON c.id = e.courseid
1141 $groupjoin
1142 WHERE
1143 (ra.contextid = :contextid $parentcontexts)
1144 AND c.id = :courseid
1145 AND ue.status = 0
1146 AND e.status = 0
1147 AND ue.timestart < :now1
1148 AND (ue.timeend > :now2 OR ue.timeend = 0)
1149 $groupselect
1150 $roles
1153 $now = time();
1154 $return->data['now1'] = $now;
1155 $return->data['now2'] = $now;
1156 $return->data['contextid'] = $context->id;
1157 $return->data['courseid'] = $this->course->id;
1159 return $return;
1163 * Obtains progress information across a course for all users on that course, or
1164 * for all users in a specific group. Intended for use when displaying progress.
1166 * This includes only users who, in course context, have one of the roles for
1167 * which progress is tracked (the gradebookroles admin option) and are enrolled in course.
1169 * Users are included (in the first array) even if they do not have
1170 * completion progress for any course-module.
1172 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1173 * last name
1174 * @param string $where Where clause sql (optional)
1175 * @param array $where_params Where clause params (optional)
1176 * @param int $groupid Group ID or 0 (default)/false for all groups
1177 * @param int $pagesize Number of users to actually return (optional)
1178 * @param int $start User to start at if paging (optional)
1179 * @param context $extracontext If set, includes extra user information fields
1180 * as appropriate to display for current user in this context
1181 * @return stdClass with ->total and ->start (same as $start) and ->users;
1182 * an array of user objects (like mdl_user id, firstname, lastname)
1183 * containing an additional ->progress array of coursemoduleid => completionstate
1185 public function get_progress_all($where = '', $where_params = array(), $groupid = 0,
1186 $sort = '', $pagesize = '', $start = '', context $extracontext = null) {
1187 global $CFG, $DB;
1189 // Get list of applicable users
1190 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort,
1191 $start, $pagesize, $extracontext);
1193 // Get progress information for these users in groups of 1, 000 (if needed)
1194 // to avoid making the SQL IN too long
1195 $results = array();
1196 $userids = array();
1197 foreach ($users as $user) {
1198 $userids[] = $user->id;
1199 $results[$user->id] = $user;
1200 $results[$user->id]->progress = array();
1203 for($i=0; $i<count($userids); $i+=1000) {
1204 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
1206 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1207 array_splice($params, 0, 0, array($this->course->id));
1208 $rs = $DB->get_recordset_sql("
1209 SELECT
1210 cmc.*
1211 FROM
1212 {course_modules} cm
1213 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1214 WHERE
1215 cm.course=? AND cmc.userid $insql", $params);
1216 foreach ($rs as $progress) {
1217 $progress = (object)$progress;
1218 $results[$progress->userid]->progress[$progress->coursemoduleid] = $progress;
1220 $rs->close();
1223 return $results;
1227 * Called by grade code to inform the completion system when a grade has
1228 * been changed. If the changed grade is used to determine completion for
1229 * the course-module, then the completion status will be updated.
1231 * @param stdClass|cm_info $cm Course-module for item that owns grade
1232 * @param grade_item $item Grade item
1233 * @param stdClass $grade
1234 * @param bool $deleted
1236 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1237 // Bail out now if completion is not enabled for course-module, it is enabled
1238 // but is set to manual, grade is not used to compute completion, or this
1239 // is a different numbered grade
1240 if (!$this->is_enabled($cm) ||
1241 $cm->completion == COMPLETION_TRACKING_MANUAL ||
1242 is_null($cm->completiongradeitemnumber) ||
1243 $item->itemnumber != $cm->completiongradeitemnumber) {
1244 return;
1247 // What is the expected result based on this grade?
1248 if ($deleted) {
1249 // Grade being deleted, so only change could be to make it incomplete
1250 $possibleresult = COMPLETION_INCOMPLETE;
1251 } else {
1252 $possibleresult = self::internal_get_grade_state($item, $grade);
1255 // OK, let's update state based on this
1256 $this->update_state($cm, $possibleresult, $grade->userid);
1260 * Calculates the completion state that would result from a graded item
1261 * (where grade-based completion is turned on) based on the actual grade
1262 * and settings.
1264 * Internal function. Not private, so we can unit-test it.
1266 * @param grade_item $item an instance of grade_item
1267 * @param grade_grade $grade an instance of grade_grade
1268 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1270 public static function internal_get_grade_state($item, $grade) {
1271 if (!$grade) {
1272 return COMPLETION_INCOMPLETE;
1274 // Conditions to show pass/fail:
1275 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1276 // b) Grade is visible (neither hidden nor hidden-until)
1277 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
1278 // Use final grade if set otherwise raw grade
1279 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
1281 // We are displaying and tracking pass/fail
1282 if ($score >= $item->gradepass) {
1283 return COMPLETION_COMPLETE_PASS;
1284 } else {
1285 return COMPLETION_COMPLETE_FAIL;
1287 } else {
1288 // Not displaying pass/fail, so just if there is a grade
1289 if (!is_null($grade->finalgrade) || !is_null($grade->rawgrade)) {
1290 // Grade exists, so maybe complete now
1291 return COMPLETION_COMPLETE;
1292 } else {
1293 // Grade does not exist, so maybe incomplete now
1294 return COMPLETION_INCOMPLETE;
1300 * Aggregate activity completion state
1302 * @param int $type Aggregation type (COMPLETION_* constant)
1303 * @param bool $old Old state
1304 * @param bool $new New state
1305 * @return bool
1307 public static function aggregate_completion_states($type, $old, $new) {
1308 if ($type == COMPLETION_AND) {
1309 return $old && $new;
1310 } else {
1311 return $old || $new;
1316 * This is to be used only for system errors (things that shouldn't happen)
1317 * and not user-level errors.
1319 * @global type $CFG
1320 * @param string $error Error string (will not be displayed to user unless debugging is enabled)
1321 * @throws moodle_exception Exception with the error string as debug info
1323 public function internal_systemerror($error) {
1324 global $CFG;
1325 throw new moodle_exception('err_system','completion',
1326 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
1330 * For testing only. Wipes information cached in user session.
1332 public static function wipe_session_cache() {
1333 global $SESSION;
1334 unset($SESSION->completioncache);
1335 unset($SESSION->completioncacheuserid);