3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * Contains a class used for tracking whether activities have been completed
20 * by students ('completion')
22 * Completion top-level options (admin setting enablecompletion)
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
96 define('COMPLETION_OR', false);
97 /** Completion details should be ANDed together and you should return true if
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
131 * Completion criteria
134 * @see completion_info->get_criteria()
139 * Return array of aggregation methods
143 public static function get_aggregation_methods() {
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.
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() {
171 return !empty($CFG->enablecompletion
);
175 * Checks whether completion is enabled in a particular course and possibly
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) {
190 // First check global completion
191 if (!isset($CFG->enablecompletion
) ||
$CFG->enablecompletion
== COMPLETION_DISABLED
) {
192 return COMPLETION_DISABLED
;
195 // Check course completion
196 if ($this->course
->enablecompletion
== COMPLETION_DISABLED
) {
197 return COMPLETION_DISABLED
;
200 // If there was no $cm and we got this far, then it's enabled
202 return COMPLETION_ENABLED
;
205 // Return course-module completion value
206 return $cm->completion
;
210 * Displays the 'Your progress' help icon, if completion tracking is enabled.
211 * Just prints the result of display_help_icon().
212 * @deprecated Use display_help_icon instead.
215 public function print_help_icon() {
216 print $this->display_help_icon();
220 * Returns the 'Your progress' help icon, if completion tracking is enabled.
222 * @return string HTML code for help icon, or blank if not needed
224 public function display_help_icon() {
225 global $PAGE, $OUTPUT;
227 if ($this->is_enabled() && !$PAGE->user_is_editing() && isloggedin() && !isguestuser()) {
228 $result .= '<span id = "completionprogressid" class="completionprogress">'.get_string('yourprogress','completion').' ';
229 $result .= $OUTPUT->help_icon('completionicons', 'completion');
230 $result .= '</span>';
236 * Get a course completion for a user
238 * @param $user_id int User id
239 * @param $criteriatype int Specific criteria type to return
240 * @return false|completion_criteria_completion
242 public function get_completion($user_id, $criteriatype) {
243 $completions = $this->get_completions($user_id, $criteriatype);
245 if (empty($completions)) {
247 } elseif (count($completions) > 1) {
248 print_error('multipleselfcompletioncriteria', 'completion');
251 return $completions[0];
255 * Get all course criteria's completion objects for a user
257 * @param $user_id int User id
258 * @param $criteriatype int optional Specific criteria type to return
261 public function get_completions($user_id, $criteriatype = null) {
262 $criterion = $this->get_criteria($criteriatype);
264 $completions = array();
266 foreach ($criterion as $criteria) {
268 'course' => $this->course_id
,
269 'userid' => $user_id,
270 'criteriaid' => $criteria->id
273 $completion = new completion_criteria_completion($params);
274 $completion->attach_criteria($criteria);
276 $completions[] = $completion;
283 * Get completion object for a user and a criteria
285 * @param $user_id int User id
286 * @param $criteria completion_criteria Criteria object
287 * @return completion_criteria_completion
289 public function get_user_completion($user_id, $criteria) {
291 'criteriaid' => $criteria->id
,
295 $completion = new completion_criteria_completion($params);
300 * Check if course has completion criteria set
305 public function has_criteria() {
306 $criteria = $this->get_criteria();
308 return (bool) count($criteria);
313 * Get course completion criteria
315 * @param $criteriatype int optional Specific criteria type to return
318 public function get_criteria($criteriatype = null) {
320 // Fill cache if empty
321 if (!is_array($this->criteria
)) {
325 'course' => $this->course
->id
328 // Load criteria from database
329 $records = (array)$DB->get_records('course_completion_criteria', $params);
331 // Build array of criteria objects
332 $this->criteria
= array();
333 foreach ($records as $record) {
334 $this->criteria
[$record->id
] = completion_criteria
::factory($record);
338 // If after all criteria
339 if ($criteriatype === null) {
340 return $this->criteria
;
343 // If we are only after a specific criteria type
345 foreach ($this->criteria
as $criterion) {
347 if ($criterion->criteriatype
!= $criteriatype) {
351 $criteria[$criterion->id
] = $criterion;
358 * Get aggregation method
360 * @param $criteriatype int optional If none supplied, get overall aggregation method
363 public function get_aggregation_method($criteriatype = null) {
365 'course' => $this->course_id
,
366 'criteriatype' => $criteriatype
369 $aggregation = new completion_aggregation($params);
371 if (!$aggregation->id
) {
372 $aggregation->method
= COMPLETION_AGGREGATION_ALL
;
375 return $aggregation->method
;
379 * Get incomplete course completion criteria
383 public function get_incomplete_criteria() {
384 $incomplete = array();
386 foreach ($this->get_criteria() as $criteria) {
387 if (!$criteria->is_complete()) {
388 $incomplete[] = $criteria;
396 * Clear old course completion criteria
398 public function clear_criteria() {
400 $DB->delete_records('course_completion_criteria', array('course' => $this->course_id
));
401 $DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id
));
403 $this->delete_course_completion_data();
407 * Has the supplied user completed this course
409 * @param $user_id int User's id
412 public function is_course_complete($user_id) {
414 'userid' => $user_id,
415 'course' => $this->course_id
418 $ccompletion = new completion_completion($params);
419 return $ccompletion->is_complete();
423 * Updates (if necessary) the completion state of activity $cm for the given
426 * For manual completion, this function is called when completion is toggled
427 * with $possibleresult set to the target state.
429 * For automatic completion, this function should be called every time a module
430 * does something which might influence a user's completion state. For example,
431 * if a forum provides options for marking itself 'completed' once a user makes
432 * N posts, this function should be called every time a user makes a new post.
433 * [After the post has been saved to the database]. When calling, you do not
434 * need to pass in the new completion state. Instead this function carries out
435 * completion calculation by checking grades and viewed state itself, and
436 * calling the involved module via modulename_get_completion_state() to check
437 * module-specific conditions.
441 * @uses COMPLETION_COMPLETE
442 * @uses COMPLETION_INCOMPLETE
443 * @uses COMPLETION_COMPLETE_PASS
444 * @uses COMPLETION_COMPLETE_FAIL
445 * @uses COMPLETION_TRACKING_MANUAL
446 * @param object $cm Course-module
447 * @param int $possibleresult Expected completion result. If the event that
448 * has just occurred (e.g. add post) can only result in making the activity
449 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
450 * has just occurred (e.g. delete post) can only result in making the activity
451 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
452 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
453 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
454 * processing early if the user's completion state already matches the expected
455 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
456 * must be used; these directly set the specified state.
457 * @param int $userid User ID to be updated. Default 0 = current user
460 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN
, $userid=0) {
461 global $USER, $SESSION;
463 // Do nothing if completion is not enabled for that activity
464 if (!$this->is_enabled($cm)) {
468 // Get current value of completion state and do nothing if it's same as
469 // the possible result of this change. If the change is to COMPLETE and the
470 // current value is one of the COMPLETE_xx subtypes, ignore that as well
471 $current = $this->get_data($cm, false, $userid);
472 if ($possibleresult == $current->completionstate ||
473 ($possibleresult == COMPLETION_COMPLETE
&&
474 ($current->completionstate
== COMPLETION_COMPLETE_PASS ||
475 $current->completionstate
== COMPLETION_COMPLETE_FAIL
))) {
479 if ($cm->completion
== COMPLETION_TRACKING_MANUAL
) {
480 // For manual tracking we set the result directly
481 switch($possibleresult) {
482 case COMPLETION_COMPLETE
:
483 case COMPLETION_INCOMPLETE
:
484 $newstate = $possibleresult;
487 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
491 // Automatic tracking; get new state
492 $newstate = $this->internal_get_state($cm, $userid, $current);
495 // If changed, update
496 if ($newstate != $current->completionstate
) {
497 $current->completionstate
= $newstate;
498 $current->timemodified
= time();
499 $this->internal_set_data($cm, $current);
504 * Calculates the completion state for an activity and user.
506 * Internal function. Not private, so we can unit-test it.
511 * @uses COMPLETION_VIEW_REQUIRED
512 * @uses COMPLETION_NOT_VIEWED
513 * @uses COMPLETION_INCOMPLETE
514 * @uses FEATURE_COMPLETION_HAS_RULES
515 * @uses COMPLETION_COMPLETE
516 * @uses COMPLETION_AND
517 * @param object $cm Activity
518 * @param int $userid ID of user
519 * @param object $current Previous completion information from database
522 function internal_get_state($cm, $userid, $current) {
523 global $USER, $DB, $CFG;
531 if ($cm->completionview
== COMPLETION_VIEW_REQUIRED
&&
532 $current->viewed
== COMPLETION_NOT_VIEWED
) {
534 return COMPLETION_INCOMPLETE
;
537 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
538 if (!isset($cm->modname
)) {
539 $cm->modname
= $DB->get_field('modules', 'name', array('id'=>$cm->module
));
542 $newstate = COMPLETION_COMPLETE
;
545 if (!is_null($cm->completiongradeitemnumber
)) {
546 require_once($CFG->libdir
.'/gradelib.php');
547 $item = grade_item
::fetch(array('courseid'=>$cm->course
, 'itemtype'=>'mod',
548 'itemmodule'=>$cm->modname
, 'iteminstance'=>$cm->instance
,
549 'itemnumber'=>$cm->completiongradeitemnumber
));
551 // Fetch 'grades' (will be one or none)
552 $grades = grade_grade
::fetch_users_grades($item, array($userid), false);
553 if (empty($grades)) {
555 return COMPLETION_INCOMPLETE
;
557 if (count($grades) > 1) {
558 $this->internal_systemerror("Unexpected result: multiple grades for
559 item '{$item->id}', user '{$userid}'");
561 $newstate = $this->internal_get_grade_state($item, reset($grades));
562 if ($newstate == COMPLETION_INCOMPLETE
) {
563 return COMPLETION_INCOMPLETE
;
567 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
568 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
572 if (plugin_supports('mod', $cm->modname
, FEATURE_COMPLETION_HAS_RULES
)) {
573 $function = $cm->modname
.'_get_completion_state';
574 if (!function_exists($function)) {
575 $this->internal_systemerror("Module {$cm->modname} claims to support
576 FEATURE_COMPLETION_HAS_RULES but does not have required
577 {$cm->modname}_get_completion_state function");
579 if (!$function($this->course
, $cm, $userid, COMPLETION_AND
)) {
580 return COMPLETION_INCOMPLETE
;
590 * Marks a module as viewed.
592 * Should be called whenever a module is 'viewed' (it is up to the module how to
593 * determine that). Has no effect if viewing is not set as a completion condition.
595 * Note that this function must be called before you print the page header because
596 * it is possible that the navigation block may depend on it. If you call it after
597 * printing the header, it shows a developer debug warning.
598 * @uses COMPLETION_VIEW_NOT_REQUIRED
599 * @uses COMPLETION_VIEWED
600 * @uses COMPLETION_COMPLETE
601 * @param object $cm Activity
602 * @param int $userid User ID or 0 (default) for current user
605 public function set_module_viewed($cm, $userid=0) {
606 global $PAGE, $UNITTEST;
607 if ($PAGE->headerprinted
&& empty($UNITTEST->running
)) {
608 debugging('set_module_viewed must be called before header is printed',
611 // Don't do anything if view condition is not turned on
612 if ($cm->completionview
== COMPLETION_VIEW_NOT_REQUIRED ||
!$this->is_enabled($cm)) {
615 // Get current completion state
616 $data = $this->get_data($cm, $userid);
617 // If we already viewed it, don't do anything
618 if ($data->viewed
== COMPLETION_VIEWED
) {
621 // OK, change state, save it, and update completion
622 $data->viewed
= COMPLETION_VIEWED
;
623 $this->internal_set_data($cm, $data);
624 $this->update_state($cm, COMPLETION_COMPLETE
, $userid);
628 * Determines how much completion data exists for an activity. This is used when
629 * deciding whether completion information should be 'locked' in the module
633 * @param object $cm Activity
634 * @return int The number of users who have completion data stored for this
635 * activity, 0 if none
637 public function count_user_data($cm) {
640 return $DB->get_field_sql("
644 {course_modules_completion}
646 coursemoduleid=? AND completionstate<>0", array($cm->id
));
650 * Determines how much course completion data exists for a course. This is used when
651 * deciding whether completion information should be 'locked' in the completion
652 * settings form and activity completion settings.
655 * @param int $user_id Optionally only get course completion data for a single user
656 * @return int The number of users who have completion data stored for this
659 public function count_course_user_data($user_id = null) {
666 {course_completion_crit_compl}
671 $params = array($this->course_id
);
673 // Limit data to a single user if an ID is supplied
675 $sql .= ' AND userid = ?';
676 $params[] = $user_id;
679 return $DB->get_field_sql($sql, $params);
683 * Check if this course's completion criteria should be locked
687 public function is_course_locked() {
688 return (bool) $this->count_course_user_data();
692 * Deletes all course completion completion data.
694 * Intended to be used when unlocking completion criteria settings.
699 public function delete_course_completion_data() {
702 $DB->delete_records('course_completions', array('course' => $this->course_id
));
703 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id
));
707 * Deletes completion state related to an activity for all users.
709 * Intended for use only when the activity itself is deleted.
713 * @param object $cm Activity
715 public function delete_all_state($cm) {
716 global $SESSION, $DB;
718 // Delete from database
719 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id
));
721 // Erase cache data for current user if applicable
722 if (isset($SESSION->completioncache
) &&
723 array_key_exists($cm->course
, $SESSION->completioncache
) &&
724 array_key_exists($cm->id
, $SESSION->completioncache
[$cm->course
])) {
726 unset($SESSION->completioncache
[$cm->course
][$cm->id
]);
729 // Check if there is an associated course completion criteria
730 $criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY
);
732 foreach ($criteria as $criterion) {
733 if ($criterion->moduleinstance
== $cm->id
) {
734 $acriteria = $criterion;
740 // Delete all criteria completions relating to this activity
741 $DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id
, 'criteriaid' => $acriteria->id
));
742 $DB->delete_records('course_completions', array('course' => $this->course_id
));
747 * Recalculates completion state related to an activity for all users.
749 * Intended for use if completion conditions change. (This should be avoided
750 * as it may cause some things to become incomplete when they were previously
751 * complete, with the effect - for example - of hiding a later activity that
752 * was previously available.)
754 * Resetting state of manual tickbox has same result as deleting state for
758 * @uses COMPLETION_TRACKING_MANUAL
759 * @uses COMPLETION_UNKNOWN
760 * @param object $cm Activity
762 public function reset_all_state($cm) {
765 if ($cm->completion
== COMPLETION_TRACKING_MANUAL
) {
766 $this->delete_all_state($cm);
769 // Get current list of users with completion state
770 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id
), '', 'userid');
771 $keepusers = array();
772 foreach ($rs as $rec) {
773 $keepusers[] = $rec->userid
;
777 // Delete all existing state [also clears session cache for current user]
778 $this->delete_all_state($cm);
780 // Merge this with list of planned users (according to roles)
781 $trackedusers = $this->get_tracked_users();
782 foreach ($trackedusers as $trackeduser) {
783 $keepusers[] = $trackeduser->id
;
785 $keepusers = array_unique($keepusers);
787 // Recalculate state for each kept user
788 foreach ($keepusers as $keepuser) {
789 $this->update_state($cm, COMPLETION_UNKNOWN
, $keepuser);
794 * Obtains completion data for a particular activity and user (from the
795 * session cache if available, or by SQL query)
801 * @uses COMPLETION_CACHE_EXPIRY
802 * @param object $cm Activity; only required field is ->id
803 * @param bool $wholecourse If true (default false) then, when necessary to
804 * fill the cache, retrieves information from the entire course not just for
806 * @param int $userid User ID or 0 (default) for current user
807 * @param array $modinfo Supply the value here - this is used for unit
808 * testing and so that it can be called recursively from within
809 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
810 * Otherwise the method calls get_fast_modinfo itself.
811 * @return object Completion data (record from course_modules_completion)
813 public function get_data($cm, $wholecourse=false, $userid=0, $modinfo=null) {
814 global $USER, $CFG, $SESSION, $DB;
821 // Is this the current user?
822 $currentuser = $userid==$USER->id
;
824 if ($currentuser && is_object($SESSION)) {
825 // Make sure cache is present and is for current user (loginas
827 if (!isset($SESSION->completioncache
) ||
$SESSION->completioncacheuserid
!=$USER->id
) {
828 $SESSION->completioncache
= array();
829 $SESSION->completioncacheuserid
= $USER->id
;
831 // Expire any old data from cache
832 foreach ($SESSION->completioncache
as $courseid=>$activities) {
833 if (empty($activities['updated']) ||
$activities['updated'] < time()-COMPLETION_CACHE_EXPIRY
) {
834 unset($SESSION->completioncache
[$courseid]);
837 // See if requested data is present, if so use cache to get it
838 if (isset($SESSION->completioncache
) &&
839 array_key_exists($this->course
->id
, $SESSION->completioncache
) &&
840 array_key_exists($cm->id
, $SESSION->completioncache
[$this->course
->id
])) {
841 return $SESSION->completioncache
[$this->course
->id
][$cm->id
];
845 // Not there, get via SQL
846 if ($currentuser && $wholecourse) {
847 // Get whole course data for cache
848 $alldatabycmc = $DB->get_records_sql("
853 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
855 cm.course=? AND cmc.userid=?", array($this->course
->id
, $userid));
860 foreach ($alldatabycmc as $data) {
861 $alldata[$data->coursemoduleid
] = $data;
865 // Get the module info and build up condition info for each one
866 if (empty($modinfo)) {
867 $modinfo = get_fast_modinfo($this->course
, $userid);
869 foreach ($modinfo->cms
as $othercm) {
870 if (array_key_exists($othercm->id
, $alldata)) {
871 $data = $alldata[$othercm->id
];
873 // Row not present counts as 'not complete'
874 $data = new StdClass
;
876 $data->coursemoduleid
= $othercm->id
;
877 $data->userid
= $userid;
878 $data->completionstate
= 0;
880 $data->timemodified
= 0;
882 $SESSION->completioncache
[$this->course
->id
][$othercm->id
] = $data;
884 $SESSION->completioncache
[$this->course
->id
]['updated'] = time();
886 if (!isset($SESSION->completioncache
[$this->course
->id
][$cm->id
])) {
887 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
889 return $SESSION->completioncache
[$this->course
->id
][$cm->id
];
893 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id
, 'userid'=>$userid));
894 if ($data == false) {
895 // Row not present counts as 'not complete'
896 $data = new StdClass
;
898 $data->coursemoduleid
= $cm->id
;
899 $data->userid
= $userid;
900 $data->completionstate
= 0;
902 $data->timemodified
= 0;
907 $SESSION->completioncache
[$this->course
->id
][$cm->id
] = $data;
908 // For single updates, only set date if it was empty before
909 if (empty($SESSION->completioncache
[$this->course
->id
]['updated'])) {
910 $SESSION->completioncache
[$this->course
->id
]['updated'] = time();
919 * Updates completion data for a particular coursemodule and user (user is
920 * determined from $data).
922 * (Internal function. Not private, so we can unit-test it.)
927 * @param object $cm Activity
928 * @param object $data Data about completion for that user
930 function internal_set_data($cm, $data) {
931 global $USER, $SESSION, $DB;
934 // Has real (nonzero) id meaning that a database row exists
935 $DB->update_record('course_modules_completion', $data);
937 // Didn't exist before, needs creating
938 $data->id
= $DB->insert_record('course_modules_completion', $data);
941 if ($data->userid
== $USER->id
) {
942 $SESSION->completioncache
[$cm->course
][$cm->id
] = $data;
944 get_fast_modinfo($reset);
949 * Obtains a list of activities for which completion is enabled on the
950 * course. The list is ordered by the section order of those activities.
953 * @uses COMPLETION_TRACKING_NONE
954 * @param array $modinfo For unit testing only, supply the value
955 * here. Otherwise the method calls get_fast_modinfo
956 * @return array Array from $cmid => $cm of all activities with completion enabled,
957 * empty array if none
959 public function get_activities($modinfo=null) {
962 // Obtain those activities which have completion turned on
963 $withcompletion = $DB->get_records_select('course_modules', 'course='.$this->course
->id
.
964 ' AND completion<>'.COMPLETION_TRACKING_NONE
);
965 if (!$withcompletion) {
969 // Use modinfo to get section order and also add in names
970 if (empty($modinfo)) {
971 $modinfo = get_fast_modinfo($this->course
);
974 foreach ($modinfo->sections
as $sectioncms) {
975 foreach ($sectioncms as $cmid) {
976 if (array_key_exists($cmid, $withcompletion)) {
977 $result[$cmid] = $withcompletion[$cmid];
978 $result[$cmid]->modname
= $modinfo->cms
[$cmid]->modname
;
979 $result[$cmid]->name
= $modinfo->cms
[$cmid]->name
;
989 * Checks to see if the userid supplied has a tracked role in
992 * @param $userid User id
995 function is_tracked_user($userid) {
998 $tracked = $this->generate_tracked_user_sql();
1000 $sql = "SELECT u.id ";
1001 $sql .= $tracked->sql
;
1002 $sql .= ' AND u.id = :userid';
1004 $params = $tracked->data
;
1005 $params['userid'] = (int)$userid;
1006 return $DB->record_exists_sql($sql, $params);
1011 * Return number of users whose progress is tracked in this course
1013 * Optionally supply a search's where clause, or a group id
1015 * @param string $where Where clause sql
1016 * @param array $where_params Where clause params
1017 * @param int $groupid Group id
1020 function get_num_tracked_users($where = '', $where_params = array(), $groupid = 0) {
1023 $tracked = $this->generate_tracked_user_sql($groupid);
1025 $sql = "SELECT COUNT(u.id) ";
1026 $sql .= $tracked->sql
;
1029 $sql .= " AND $where";
1032 $params = array_merge($tracked->data
, $where_params);
1033 return $DB->count_records_sql($sql, $params);
1038 * Return array of users whose progress is tracked in this course
1040 * Optionally supply a search's where caluse, group id, sorting, paging
1042 * @param string $where Where clause sql (optional)
1043 * @param array $where_params Where clause params (optional)
1044 * @param integer $groupid Group ID to restrict to (optional)
1045 * @param string $sort Order by clause (optional)
1046 * @param integer $limitfrom Result start (optional)
1047 * @param integer $limitnum Result max size (optional)
1050 function get_tracked_users($where = '', $where_params = array(), $groupid = 0,
1051 $sort = '', $limitfrom = '', $limitnum = '') {
1055 $tracked = $this->generate_tracked_user_sql($groupid);
1056 $params = $tracked->data
;
1066 $sql .= $tracked->sql
;
1069 $sql .= " AND $where";
1070 $params = array_merge($params, $where_params);
1074 $sql .= " ORDER BY $sort";
1077 $users = $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
1078 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
1091 function generate_tracked_user_sql($groupid = 0) {
1094 $return = new stdClass();
1096 $return->data
= array();
1098 if (!empty($CFG->gradebookroles
)) {
1099 $roles = ' AND ra.roleid IN ('.$CFG->gradebookroles
.')';
1101 // This causes it to default to everyone (if there is no student role)
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.' )';
1116 $groupjoin = "JOIN {groups_members} gm
1117 ON gm.userid = u.id";
1118 $groupselect = " AND gm.groupid = :groupid ";
1120 $return->data
['groupid'] = $groupid;
1127 {role_assignments} ra
1133 {user_enrolments} ue
1137 ON e.id = ue.enrolid
1140 ON c.id = e.courseid
1143 (ra.contextid = :contextid $parentcontexts)
1144 AND c.id = :courseid
1147 AND ue.timestart < :now1
1148 AND (ue.timeend > :now2 OR ue.timeend = 0)
1154 $return->data
['now1'] = $now;
1155 $return->data
['now2'] = $now;
1156 $return->data
['contextid'] = $context->id
;
1157 $return->data
['courseid'] = $this->course
->id
;
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.
1174 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
1176 * @param string $where Where clause sql (optional)
1177 * @param array $where_params Where clause params (optional)
1178 * @param int $groupid Group ID or 0 (default)/false for all groups
1179 * @param int $pagesize Number of users to actually return (optional)
1180 * @param int $start User to start at if paging (optional)
1181 * @return Object 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 = '') {
1189 // Get list of applicable users
1190 $users = $this->get_tracked_users($where, $where_params, $groupid, $sort, $start, $pagesize);
1192 // Get progress information for these users in groups of 1, 000 (if needed)
1193 // to avoid making the SQL IN too long
1196 foreach ($users as $user) {
1197 $userids[] = $user->id
;
1198 $results[$user->id
] = $user;
1199 $results[$user->id
]->progress
= array();
1202 for($i=0; $i<count($userids); $i+
=1000) {
1203 $blocksize = count($userids)-$i < 1000 ?
count($userids)-$i : 1000;
1205 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
1206 array_splice($params, 0, 0, array($this->course
->id
));
1207 $rs = $DB->get_recordset_sql("
1212 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
1214 cm.course=? AND cmc.userid $insql
1216 foreach ($rs as $progress) {
1217 $progress = (object)$progress;
1218 $results[$progress->userid
]->progress
[$progress->coursemoduleid
] = $progress;
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 * @uses COMPLETION_TRACKING_MANUAL
1232 * @uses COMPLETION_INCOMPLETE
1233 * @param object $cm Course-module for item that owns grade
1234 * @param grade_item $item Grade item
1235 * @param object $grade
1236 * @param bool $deleted
1239 public function inform_grade_changed($cm, $item, $grade, $deleted) {
1240 // Bail out now if completion is not enabled for course-module, it is enabled
1241 // but is set to manual, grade is not used to compute completion, or this
1242 // is a different numbered grade
1243 if (!$this->is_enabled($cm) ||
1244 $cm->completion
== COMPLETION_TRACKING_MANUAL ||
1245 is_null($cm->completiongradeitemnumber
) ||
1246 $item->itemnumber
!= $cm->completiongradeitemnumber
) {
1250 // What is the expected result based on this grade?
1252 // Grade being deleted, so only change could be to make it incomplete
1253 $possibleresult = COMPLETION_INCOMPLETE
;
1255 $possibleresult = $this->internal_get_grade_state($item, $grade);
1258 // OK, let's update state based on this
1259 $this->update_state($cm, $possibleresult, $grade->userid
);
1263 * Calculates the completion state that would result from a graded item
1264 * (where grade-based completion is turned on) based on the actual grade
1267 * Internal function. Not private, so we can unit-test it.
1269 * @uses COMPLETION_INCOMPLETE
1270 * @uses COMPLETION_COMPLETE_PASS
1271 * @uses COMPLETION_COMPLETE_FAIL
1272 * @uses COMPLETION_COMPLETE
1273 * @param object $item grade_item
1274 * @param object $grade grade_grade
1275 * @return int Completion state e.g. COMPLETION_INCOMPLETE
1277 function internal_get_grade_state($item, $grade) {
1279 return COMPLETION_INCOMPLETE
;
1281 // Conditions to show pass/fail:
1282 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
1283 // b) Grade is visible (neither hidden nor hidden-until)
1284 if ($item->gradepass
&& $item->gradepass
> 0.000009 && !$item->hidden
) {
1285 // Use final grade if set otherwise raw grade
1286 $score = !is_null($grade->finalgrade
) ?
$grade->finalgrade
: $grade->rawgrade
;
1288 // We are displaying and tracking pass/fail
1289 if ($score >= $item->gradepass
) {
1290 return COMPLETION_COMPLETE_PASS
;
1292 return COMPLETION_COMPLETE_FAIL
;
1295 // Not displaying pass/fail, so just if there is a grade
1296 if (!is_null($grade->finalgrade
) ||
!is_null($grade->rawgrade
)) {
1297 // Grade exists, so maybe complete now
1298 return COMPLETION_COMPLETE
;
1300 // Grade does not exist, so maybe incomplete now
1301 return COMPLETION_INCOMPLETE
;
1307 * This is to be used only for system errors (things that shouldn't happen)
1308 * and not user-level errors.
1311 * @param string $error Error string (will not be displayed to user unless
1312 * debugging is enabled)
1313 * @return void Throws moodle_exception Exception with the error string as debug info
1315 function internal_systemerror($error) {
1317 throw new moodle_exception('err_system','completion',
1318 $CFG->wwwroot
.'/course/view.php?id='.$this->course
->id
,null,$error);
1322 * For testing only. Wipes information cached in user session.
1326 static function wipe_session_cache() {
1328 unset($SESSION->completioncache
);
1329 unset($SESSION->completioncacheuserid
);