clilib.php MDL-19236 added phpdocs and copyrights
[moodle.git] / lib / completionlib.php
CommitLineData
4e781c7b 1<?php
2// Contains a class used for tracking whether activities have been completed
3// by students ('completion')
4
5// Completion top-level options (admin setting enablecompletion)
6
7/** The completion system is enabled in this site/course */
0d5d12bd 8define('COMPLETION_ENABLED', 1);
4e781c7b 9/** The completion system is not enabled in this site/course */
0d5d12bd 10define('COMPLETION_DISABLED', 0);
4e781c7b 11
12// Completion tracking options per-activity (course_modules/completion)
13
14/** Completion tracking is disabled for this activity */
0d5d12bd 15define('COMPLETION_TRACKING_NONE', 0);
4e781c7b 16/** Manual completion tracking (user ticks box) is enabled for this activity */
0d5d12bd 17define('COMPLETION_TRACKING_MANUAL', 1);
4e781c7b 18/** Automatic completion tracking (system ticks box) is enabled for this activity */
0d5d12bd 19define('COMPLETION_TRACKING_AUTOMATIC', 2);
4e781c7b 20
21// Completion state values (course_modules_completion/completionstate)
22
23/** The user has not completed this activity. */
0d5d12bd 24define('COMPLETION_INCOMPLETE', 0);
4e781c7b 25/** The user has completed this activity. It is not specified whether they have
26 * passed or failed it. */
0d5d12bd 27define('COMPLETION_COMPLETE', 1);
4e781c7b 28/** The user has completed this activity with a grade above the pass mark. */
0d5d12bd 29define('COMPLETION_COMPLETE_PASS', 2);
4e781c7b 30/** The user has completed this activity but their grade is less than the pass mark */
0d5d12bd 31define('COMPLETION_COMPLETE_FAIL', 3);
4e781c7b 32
0d5d12bd 33// Completion effect changes (used only in update_state)
4e781c7b 34
35/** The effect of this change to completion status is unknown. */
0d5d12bd 36define('COMPLETION_UNKNOWN', -1);
37/** The user's grade has changed, so their new state might be
4e781c7b 38 * COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL. */
39// TODO Is this useful?
0d5d12bd 40define('COMPLETION_GRADECHANGE', -2);
4e781c7b 41
42// Whether view is required to create an activity (course_modules/completionview)
43
44/** User must view this activity */
0d5d12bd 45define('COMPLETION_VIEW_REQUIRED', 1);
4e781c7b 46/** User does not need to view this activity */
0d5d12bd 47define('COMPLETION_VIEW_NOT_REQUIRED', 0);
4e781c7b 48
49// Completion viewed state (course_modules_completion/viewed)
50
51/** User has viewed this activity */
0d5d12bd 52define('COMPLETION_VIEWED', 1);
4e781c7b 53/** User has not viewed this activity */
0d5d12bd 54define('COMPLETION_NOT_VIEWED', 0);
4e781c7b 55
56// Completion cacheing
57
58/** Cache expiry time in seconds (10 minutes) */
0d5d12bd 59define('COMPLETION_CACHE_EXPIRY', 10*60);
4e781c7b 60
61// Combining completion condition. This is also the value you should return
62// if you don't have any applicable conditions.
0d5d12bd 63/** Completion details should be ORed together and you should return false if
4e781c7b 64 none apply */
0d5d12bd 65define('COMPLETION_OR', false);
66/** Completion details should be ANDed together and you should return true if
4e781c7b 67 none apply */
0d5d12bd 68define('COMPLETION_AND', true);
4e781c7b 69
70/**
71 * Class represents completion information for a course.
0d5d12bd 72 * (Does not contain any data, so you can safely construct it multiple times
4e781c7b 73 * without causing any problems.)
74 */
75class completion_info {
76 private $course;
0d5d12bd 77
4e781c7b 78 /**
79 * Constructs with course details.
80 *
81 * @param object $course Moodle course object. Must have at least ->id, ->enablecompletion
82 * @return completion_info
83 */
49f6e5f4 84 public function __construct($course) {
0d5d12bd 85 $this->course = $course;
4e781c7b 86 }
87
88 /**
89 * Static function. Determines whether completion is enabled across entire
0d5d12bd 90 * site.
4e781c7b 91 *
0d5d12bd 92 * @return int COMPLETION_ENABLED (true) if completion is enabled for the site,
4e781c7b 93 * COMPLETION_DISABLED (false) if it's complete
94 */
95 public static function is_enabled_for_site() {
96 global $CFG;
1caea91e 97 return !empty($CFG->enablecompletion);
4e781c7b 98 }
0d5d12bd 99
4e781c7b 100 /**
101 * Checks whether completion is enabled in a particular course and possibly
102 * activity.
103 *
104 * @param object $cm Course-module object. If not specified, returns the course
105 * completion enable state.
106 * @return COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
107 * site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
108 * for a course-module.
109 */
110 public function is_enabled($cm=null) {
4e781c7b 111 global $CFG;
d7d87535 112
113 // First check global completion
0d5d12bd 114 if ($CFG->enablecompletion == COMPLETION_DISABLED) {
4e781c7b 115 return COMPLETION_DISABLED;
116 }
0d5d12bd 117
4e781c7b 118 // Check course completion
0d5d12bd 119 if ($this->course->enablecompletion == COMPLETION_DISABLED) {
4e781c7b 120 return COMPLETION_DISABLED;
121 }
0d5d12bd 122
4e781c7b 123 // If there was no $cm and we got this far, then it's enabled
0d5d12bd 124 if (!$cm) {
4e781c7b 125 return COMPLETION_ENABLED;
126 }
0d5d12bd 127
4e781c7b 128 // Return course-module completion value
129 return $cm->completion;
130 }
0d5d12bd 131
4e781c7b 132 /**
133 * Updates (if necessary) the completion state of activity $cm for the given
134 * user.
135 * <p>
136 * For manual completion, this function is called when completion is toggled
137 * with $possibleresult set to the target state.
138 * <p>
139 * For automatic completion, this function should be called every time a module
140 * does something which might influence a user's completion state. For example,
141 * if a forum provides options for marking itself 'completed' once a user makes
142 * N posts, this function should be called every time a user makes a new post.
143 * [After the post has been saved to the database]. When calling, you do not
144 * need to pass in the new completion state. Instead this function carries out
145 * completion calculation by checking grades and viewed state itself, and
146 * calling the involved module via modulename_get_completion_state() to check
147 * module-specific conditions.
148 *
149 * @param object $cm Course-module
150 * @param int $possibleresult Expected completion result. If the event that
151 * has just occurred (e.g. add post) can only result in making the activity
152 * complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
153 * has just occurred (e.g. delete post) can only result in making the activity
154 * not complete when it was previously complete, use COMPLETION_INCOMPLETE.
155 * Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
156 * COMPLETION_UNKNOWN significantly improves performance because it will abandon
157 * processing early if the user's completion state already matches the expected
158 * result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
159 * must be used; these directly set the specified state.
160 * @param int $userid User ID to be updated. Default 0 = current user
161 */
0d5d12bd 162 public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0) {
163 global $USER, $SESSION;
d7d87535 164
0d5d12bd 165 // Do nothing if completion is not enabled for that activity
166 if (!$this->is_enabled($cm)) {
4e781c7b 167 return;
168 }
0d5d12bd 169
4e781c7b 170 // Get current value of completion state and do nothing if it's same as
171 // the possible result of this change. If the change is to COMPLETE and the
172 // current value is one of the COMPLETE_xx subtypes, ignore that as well
0d5d12bd 173 $current = $this->get_data($cm, false, $userid);
174 if ($possibleresult == $current->completionstate ||
175 ($possibleresult == COMPLETION_COMPLETE &&
176 ($current->completionstate == COMPLETION_COMPLETE_PASS ||
177 $current->completionstate == COMPLETION_COMPLETE_FAIL))) {
4e781c7b 178 return;
179 }
0d5d12bd 180
181 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
4e781c7b 182 // For manual tracking we set the result directly
183 switch($possibleresult) {
184 case COMPLETION_COMPLETE:
185 case COMPLETION_INCOMPLETE:
0d5d12bd 186 $newstate = $possibleresult;
4e781c7b 187 break;
188 default:
189 $this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
190 }
d7d87535 191
4e781c7b 192 } else {
193 // Automatic tracking; get new state
0d5d12bd 194 $newstate = $this->internal_get_state($cm, $userid, $current);
4e781c7b 195 }
0d5d12bd 196
4e781c7b 197 // If changed, update
0d5d12bd 198 if ($newstate != $current->completionstate) {
199 $current->completionstate = $newstate;
200 $current->timemodified = time();
201 $this->internal_set_data($cm, $current);
4e781c7b 202 }
203 }
0d5d12bd 204
4e781c7b 205 /**
206 * Calculates the completion state for an activity and user.
207 * <p>
208 * (Internal function. Not private, so we can unit-test it.)
209 *
210 * @param object $cm Activity
211 * @param int $userid ID of user
212 * @param object $current Previous completion information from database
213 * @return unknown
214 */
0d5d12bd 215 function internal_get_state($cm, $userid, $current) {
7a7dbd77 216 global $USER, $DB, $CFG;
d7d87535 217
218 // Get user ID
0d5d12bd 219 if (!$userid) {
220 $userid = $USER->id;
4e781c7b 221 }
0d5d12bd 222
4e781c7b 223 // Check viewed
0d5d12bd 224 if ($cm->completionview == COMPLETION_VIEW_REQUIRED &&
225 $current->viewed == COMPLETION_NOT_VIEWED) {
226
4e781c7b 227 return COMPLETION_INCOMPLETE;
228 }
0d5d12bd 229
4e781c7b 230 // Modname hopefully is provided in $cm but just in case it isn't, let's grab it
0d5d12bd 231 if (!isset($cm->modname)) {
232 $cm->modname = $DB->get_field('modules', 'name', array('id'=>$cm->module));
4e781c7b 233 }
0d5d12bd 234
235 $newstate = COMPLETION_COMPLETE;
236
4e781c7b 237 // Check grade
0d5d12bd 238 if (!is_null($cm->completiongradeitemnumber)) {
7a7dbd77 239 require_once($CFG->libdir.'/gradelib.php');
0d5d12bd 240 $item = grade_item::fetch(array('courseid'=>$cm->course, 'itemtype'=>'mod',
241 'itemmodule'=>$cm->modname, 'iteminstance'=>$cm->instance,
4e781c7b 242 'itemnumber'=>$cm->completiongradeitemnumber));
0d5d12bd 243 if ($item) {
4e781c7b 244 // Fetch 'grades' (will be one or none)
0d5d12bd 245 $grades = grade_grade::fetch_users_grades($item, array($userid), false);
246 if (empty($grades)) {
4e781c7b 247 // No grade for user
248 return COMPLETION_INCOMPLETE;
249 }
0d5d12bd 250 if (count($grades) > 1) {
4e781c7b 251 $this->internal_systemerror("Unexpected result: multiple grades for
252 item '{$item->id}', user '{$userid}'");
253 }
0d5d12bd 254 $newstate = $this->internal_get_grade_state($item, reset($grades));
255 if ($newstate == COMPLETION_INCOMPLETE) {
4e781c7b 256 return COMPLETION_INCOMPLETE;
257 }
d7d87535 258
4e781c7b 259 } else {
260 $this->internal_systemerror("Cannot find grade item for '{$cm->modname}'
261 cm '{$cm->id}' matching number '{$cm->completiongradeitemnumber}'");
262 }
263 }
0d5d12bd 264
265 if (plugin_supports('mod', $cm->modname, FEATURE_COMPLETION_HAS_RULES)) {
266 $function = $cm->modname.'_get_completion_state';
267 if (!function_exists($function)) {
4e781c7b 268 $this->internal_systemerror("Module {$cm->modname} claims to support
269 FEATURE_COMPLETION_HAS_RULES but does not have required
270 {$cm->modname}_get_completion_state function");
271 }
0d5d12bd 272 if (!$function($this->course, $cm, $userid, COMPLETION_AND)) {
4e781c7b 273 return COMPLETION_INCOMPLETE;
274 }
275 }
0d5d12bd 276
4e781c7b 277 return $newstate;
0d5d12bd 278
4e781c7b 279 }
0d5d12bd 280
281
4e781c7b 282 /**
283 * Marks a module as viewed.
284 * <p>
285 * Should be called whenever a module is 'viewed' (it is up to the module how to
286 * determine that). Has no effect if viewing is not set as a completion condition.
287 *
288 * @param object $cm Activity
289 * @param int $userid User ID or 0 (default) for current user
290 */
0d5d12bd 291 public function set_module_viewed($cm, $userid=0) {
4e781c7b 292 // Don't do anything if view condition is not turned on
0d5d12bd 293 if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
4e781c7b 294 return;
295 }
296 // Get current completion state
0d5d12bd 297 $data = $this->get_data($cm, $userid);
4e781c7b 298 // If we already viewed it, don't do anything
0d5d12bd 299 if ($data->viewed == COMPLETION_VIEWED) {
4e781c7b 300 return;
301 }
302 // OK, change state, save it, and update completion
0d5d12bd 303 $data->viewed = COMPLETION_VIEWED;
304 $this->internal_set_data($cm, $data);
305 $this->update_state($cm, COMPLETION_COMPLETE, $userid);
4e781c7b 306 }
0d5d12bd 307
4e781c7b 308 /**
309 * Determines how much completion data exists for an activity. This is used when
310 * deciding whether completion information should be 'locked' in the module
311 * editing form.
312 *
313 * @param object $cm Activity
314 * @return int The number of users who have completion data stored for this
0d5d12bd 315 * activity, 0 if none
4e781c7b 316 */
317 public function count_user_data($cm) {
0d5d12bd 318 global $CFG, $DB;
319
4e781c7b 320 return $DB->get_field_sql("
321 SELECT
322 COUNT(1)
323 FROM
49f6e5f4 324 {course_modules_completion}
4e781c7b 325 WHERE
0d5d12bd 326 coursemoduleid=? AND completionstate<>0", array($cm->id));
4e781c7b 327 }
0d5d12bd 328
4e781c7b 329 /**
0d5d12bd 330 * Deletes completion state related to an activity for all users.
4e781c7b 331 * <p>
332 * Intended for use only when the activity itself is deleted.
333 *
334 * @param object $cm Activity
335 */
0d5d12bd 336 public function delete_all_state($cm) {
337 global $SESSION, $DB;
338
4e781c7b 339 // Delete from database
0d5d12bd 340 $DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
341
4e781c7b 342 // Erase cache data for current user if applicable
0d5d12bd 343 if (isset($SESSION->completioncache) &&
344 array_key_exists($cm->course, $SESSION->completioncache) &&
345 array_key_exists($cm->id, $SESSION->completioncache[$cm->course])) {
346
4e781c7b 347 unset($SESSION->completioncache[$cm->course][$cm->id]);
348 }
349 }
0d5d12bd 350
4e781c7b 351 /**
352 * Recalculates completion state related to an activity for all users.
353 * <p>
354 * Intended for use if completion conditions change. (This should be avoided
355 * as it may cause some things to become incomplete when they were previously
356 * complete, with the effect - for example - of hiding a later activity that
357 * was previously available.)
81f64ed3 358 * <p>
0d5d12bd 359 * Resetting state of manual tickbox has same result as deleting state for
81f64ed3 360 * it.
4e781c7b 361 * @param object $cm Activity
362 */
363 public function reset_all_state($cm) {
d7d87535 364 global $DB;
365
0d5d12bd 366 if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
81f64ed3 367 $this->delete_all_state($cm);
368 return;
369 }
4e781c7b 370 // Get current list of users with completion state
0d5d12bd 371 $rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
372 $keepusers = array();
373 foreach ($rs as $rec) {
374 $keepusers[] = $rec->userid;
4e781c7b 375 }
376 $rs->close();
0d5d12bd 377
4e781c7b 378 // Delete all existing state [also clears session cache for current user]
379 $this->delete_all_state($cm);
0d5d12bd 380
381 // Merge this with list of planned users (according to roles)
382 $trackedusers = $this->internal_get_tracked_users(false);
383 foreach ($trackedusers as $trackeduser) {
384 $keepusers[] = $trackeduser->id;
385 }
386 $keepusers = array_unique($keepusers);
387
4e781c7b 388 // Recalculate state for each kept user
0d5d12bd 389 foreach ($keepusers as $keepuser) {
390 $this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
4e781c7b 391 }
392 }
0d5d12bd 393
4e781c7b 394 /**
395 * Obtains completion data for a particular activity and user (from the
396 * session cache if available, or by SQL query)
397 *
82bd6a5e 398 * @param object $cm Activity; only required field is ->id
4e781c7b 399 * @param bool $wholecourse If true (default false) then, when necessary to
400 * fill the cache, retrieves information from the entire course not just for
401 * this one activity
402 * @param int $userid User ID or 0 (default) for current user
82bd6a5e 403 * @param array $modinfo Supply the value here - this is used for unit
404 * testing and so that it can be called recursively from within
405 * get_fast_modinfo. (Needs only list of all CMs with IDs.)
406 * Otherwise the method calls get_fast_modinfo itself.
4e781c7b 407 * @return object Completion data (record from course_modules_completion)
408 * @throws Exception In some cases where the requested course-module is not
409 * found on the specified course
410 */
0d5d12bd 411 public function get_data($cm, $wholecourse=false, $userid=0, $modinfo=null) {
0d5d12bd 412 global $USER, $CFG, $SESSION, $DB;
d7d87535 413
414 // Get user ID
0d5d12bd 415 if (!$userid) {
416 $userid = $USER->id;
4e781c7b 417 }
0d5d12bd 418
4e781c7b 419 // Is this the current user?
0d5d12bd 420 $currentuser = $userid==$USER->id;
421
422 if ($currentuser) {
423 // Make sure cache is present and is for current user (loginas
49f6e5f4 424 // changes this)
0d5d12bd 425 if (!isset($SESSION->completioncache) || $SESSION->completioncacheuserid!=$USER->id) {
426 $SESSION->completioncache = array();
427 $SESSION->completioncacheuserid = $USER->id;
4e781c7b 428 }
429 // Expire any old data from cache
0d5d12bd 430 foreach ($SESSION->completioncache as $courseid=>$activities) {
431 if (empty($activities['updated']) || $activities['updated'] < time()-COMPLETION_CACHE_EXPIRY) {
4e781c7b 432 unset($SESSION->completioncache[$courseid]);
433 }
434 }
435 // See if requested data is present, if so use cache to get it
0d5d12bd 436 if (isset($SESSION->completioncache) &&
437 array_key_exists($this->course->id, $SESSION->completioncache) &&
438 array_key_exists($cm->id, $SESSION->completioncache[$this->course->id])) {
439 return $SESSION->completioncache[$this->course->id][$cm->id];
4e781c7b 440 }
441 }
0d5d12bd 442
4e781c7b 443 // Not there, get via SQL
0d5d12bd 444 if ($currentuser && $wholecourse) {
4e781c7b 445 // Get whole course data for cache
0d5d12bd 446 $alldatabycmc = $DB->get_records_sql("
4e781c7b 447 SELECT
448 cmc.*
449 FROM
49f6e5f4 450 {course_modules} cm
451 INNER JOIN {course_modules_completion} cmc ON cmc.coursemoduleid=cm.id
0d5d12bd 452 WHERE
453 cm.course=? AND cmc.userid=?", array($this->course->id, $userid));
454
4e781c7b 455 // Reindex by cm id
0d5d12bd 456 $alldata = array();
457 if ($alldatabycmc) {
458 foreach ($alldatabycmc as $data) {
459 $alldata[$data->coursemoduleid] = $data;
4e781c7b 460 }
461 }
0d5d12bd 462
4e781c7b 463 // Get the module info and build up condition info for each one
0d5d12bd 464 if (empty($modinfo)) {
465 $modinfo = get_fast_modinfo($this->course, $userid);
4e781c7b 466 }
0d5d12bd 467 foreach ($modinfo->cms as $othercm) {
468 if (array_key_exists($othercm->id, $alldata)) {
469 $data = $alldata[$othercm->id];
4e781c7b 470 } else {
471 // Row not present counts as 'not complete'
0d5d12bd 472 $data = new StdClass;
473 $data->id = 0;
474 $data->coursemoduleid = $othercm->id;
475 $data->userid = $userid;
476 $data->completionstate = 0;
477 $data->viewed = 0;
478 $data->timemodified = 0;
4e781c7b 479 }
0d5d12bd 480 $SESSION->completioncache[$this->course->id][$othercm->id] = $data;
4e781c7b 481 }
0d5d12bd 482 $SESSION->completioncache[$this->course->id]['updated'] = time();
483
484 if (!isset($SESSION->completioncache[$this->course->id][$cm->id])) {
4e781c7b 485 $this->internal_systemerror("Unexpected error: course-module {$cm->id} could not be found on course {$this->course->id}");
486 }
487 return $SESSION->completioncache[$this->course->id][$cm->id];
d7d87535 488
4e781c7b 489 } else {
490 // Get single record
0d5d12bd 491 $data = $DB->get_record('course_modules_completion', array('coursemoduleid'=>$cm->id, 'userid'=>$userid));
492 if ($data == false) {
4e781c7b 493 // Row not present counts as 'not complete'
0d5d12bd 494 $data = new StdClass;
495 $data->id = 0;
496 $data->coursemoduleid = $cm->id;
497 $data->userid = $userid;
498 $data->completionstate = 0;
499 $data->viewed = 0;
500 $data->timemodified = 0;
4e781c7b 501 }
0d5d12bd 502
4e781c7b 503 // Put in cache
0d5d12bd 504 if ($currentuser) {
505 $SESSION->completioncache[$this->course->id][$cm->id] = $data;
4e781c7b 506 // For single updates, only set date if it was empty before
0d5d12bd 507 if (empty($SESSION->completioncache[$this->course->id]['updated'])) {
508 $SESSION->completioncache[$this->course->id]['updated'] = time();
4e781c7b 509 }
510 }
511 }
0d5d12bd 512
4e781c7b 513 return $data;
514 }
0d5d12bd 515
4e781c7b 516 /**
0d5d12bd 517 * Updates completion data for a particular coursemodule and user (user is
4e781c7b 518 * determined from $data).
519 * <p>
520 * (Internal function. Not private, so we can unit-test it.)
0d5d12bd 521 *
4e781c7b 522 * @param object $cm Activity
523 * @param object $data Data about completion for that user
524 */
0d5d12bd 525 function internal_set_data($cm, $data) {
526 global $USER, $SESSION, $DB;
d7d87535 527
0d5d12bd 528 if ($data->id) {
4e781c7b 529 // Has real (nonzero) id meaning that a database row exists
0d5d12bd 530 $DB->update_record('course_modules_completion', $data);
531 } else {
4e781c7b 532 // Didn't exist before, needs creating
0d5d12bd 533 $data->id = $DB->insert_record('course_modules_completion', $data);
4e781c7b 534 }
d7d87535 535
0d5d12bd 536 if ($data->userid == $USER->id) {
537 $SESSION->completioncache[$cm->course][$cm->id] = $data;
4e781c7b 538 }
539 }
0d5d12bd 540
4e781c7b 541 /**
0d5d12bd 542 * Obtains a list of activities for which completion is enabled on the
4e781c7b 543 * course. The list is ordered by the section order of those activities.
0d5d12bd 544 * @param array $modinfo For unit testing only, supply the value
4e781c7b 545 * here. Otherwise the method calls get_fast_modinfo
546 * @return array Array from $cmid => $cm of all activities with completion enabled,
547 * empty array if none
548 */
549 public function get_activities($modinfo=null) {
550 global $DB;
0d5d12bd 551
4e781c7b 552 // Obtain those activities which have completion turned on
0d5d12bd 553 $withcompletion = $DB->get_records_select('course_modules', 'course='.$this->course->id.
4e781c7b 554 ' AND completion<>'.COMPLETION_TRACKING_NONE);
0d5d12bd 555 if (count($withcompletion) == 0) {
4e781c7b 556 return array();
557 }
0d5d12bd 558
4e781c7b 559 // Use modinfo to get section order and also add in names
0d5d12bd 560 if (empty($modinfo)) {
561 $modinfo = get_fast_modinfo($this->course);
562 }
563 $result = array();
564 foreach ($modinfo->sections as $sectioncms) {
565 foreach ($sectioncms as $cmid) {
566 if (array_key_exists($cmid, $withcompletion)) {
567 $result[$cmid] = $withcompletion[$cmid];
568 $result[$cmid]->modname = $modinfo->cms[$cmid]->modname;
569 $result[$cmid]->name = $modinfo->cms[$cmid]->name;
4e781c7b 570 }
571 }
572 }
0d5d12bd 573
4e781c7b 574 return $result;
575 }
0d5d12bd 576
4e781c7b 577 /**
0d5d12bd 578 * Gets list of users in a course whose progress is tracked for display on the
4e781c7b 579 * progress report.
580 * @param bool $sortfirstname True to sort with firstname
581 * @param int $groupid Optionally restrict to groupid
582 * @return array Array of user objects containing id, firstname, lastname (empty if none)
583 */
0d5d12bd 584 function internal_get_tracked_users($sortfirstname, $groupid=0) {
585 global $CFG, $DB;
d7d87535 586
0d5d12bd 587 if (!empty($CFG->progresstrackedroles)) {
588 $roles = explode(', ', $CFG->progresstrackedroles);
4e781c7b 589 } else {
590 // This causes it to default to everyone (if there is no student role)
0d5d12bd 591 $roles = array();
4e781c7b 592 }
0d5d12bd 593 $users = get_role_users($roles, get_context_instance(CONTEXT_COURSE, $this->course->id), true,
594 'u.id, u.firstname, u.lastname, u.idnumber',
595 $sortfirstname ? 'u.firstname ASC' : 'u.lastname ASC', true, $groupid);
596 $users = $users ? $users : array(); // In case it returns false
4e781c7b 597 return $users;
598 }
0d5d12bd 599
4e781c7b 600 /**
601 * Obtains progress information across a course for all users on that course, or
602 * for all users in a specific group. Intended for use when displaying progress.
603 * <p>
604 * This includes only users who, in course context, have one of the roles for
605 * which progress is tracked (the progresstrackedroles admin option).
606 * <p>
607 * Users are included (in the first array) even if they do not have
608 * completion progress for any course-module.
609 *
610 * @param bool $sortfirstname If true, sort by first name, otherwise sort by
611 * last name
612 * @param int $groupid Group ID or 0 (default)/false for all groups
f9498855 613 * @return Array of user objects (like mdl_user id, firstname, lastname, idnumber)
35da0e87 614 * @param int $pagesize Number of users to actually return (0 = unlimited)
615 * @param int $start User to start at if paging (0 = first set)
616 * @return Object with ->total and ->start (same as $start) and ->users;
617 * an array of user objects (like mdl_user id, firstname, lastname)
4e781c7b 618 * containing an additional ->progress array of coursemoduleid => completionstate
619 */
35da0e87 620 public function get_progress_all($sortfirstname=false, $groupid=0,
9b0e2d66 621 $pagesize=0,$start=0) {
0d5d12bd 622 global $CFG, $DB;
35da0e87 623 $resultobject=new StdClass;
0d5d12bd 624
4e781c7b 625 // Get list of applicable users
0d5d12bd 626 $users = $this->internal_get_tracked_users($sortfirstname, $groupid);
35da0e87 627 $resultobject->start=$start;
628 $resultobject->total=count($users);
002f56ef 629 $users=array_slice($users,$start,$pagesize==0 ? count($users)-$start : $pagesize);
0d5d12bd 630
631 // Get progress information for these users in groups of 1, 000 (if needed)
4e781c7b 632 // to avoid making the SQL IN too long
35da0e87 633 $resultobject->users=array();
0d5d12bd 634 $userids = array();
635 foreach ($users as $user) {
636 $userids[] = $user->id;
35da0e87 637 $resultobject->users[$user->id]=$user;
82bd6a5e 638 $resultobject->users[$user->id]->progress=array();
0d5d12bd 639 }
640
641 for($i=0; $i<count($userids); $i+=1000) {
642 $blocksize = count($userids)-$i < 1000 ? count($userids)-$i : 1000;
643
644 list($insql, $params) = $DB->get_in_or_equal(array_slice($userids, $i, $blocksize));
645 array_splice($params, 0, 0, array($this->course->id));
646 $rs = $DB->get_recordset_sql("
4e781c7b 647SELECT
648 cmc.*
649FROM
49f6e5f4 650 {course_modules} cm
651 INNER JOIN {course_modules_completion} cmc ON cm.id=cmc.coursemoduleid
4e781c7b 652WHERE
653 cm.course=? AND cmc.userid $insql
0d5d12bd 654 ", $params);
0d5d12bd 655 foreach ($rs as $progress) {
35da0e87 656 $resultobject->users[$progress->userid]->progress[$progress->coursemoduleid]=$progress;
4e781c7b 657 }
658 $rs->close();
659 }
0d5d12bd 660
35da0e87 661 return $resultobject;
4e781c7b 662 }
0d5d12bd 663
91537a88 664 public function inform_grade_changed($cm, $item, $grade, $deleted) {
ca6b2d68 665 // Bail out now if completion is not enabled for course-module, it is enabled
666 // but is set to manual, grade is not used to compute completion, or this
667 // is a different numbered grade
0d5d12bd 668 if (!$this->is_enabled($cm) ||
ca6b2d68 669 $cm->completion == COMPLETION_TRACKING_MANUAL ||
4e781c7b 670 is_null($cm->completiongradeitemnumber) ||
0d5d12bd 671 $item->itemnumber != $cm->completiongradeitemnumber) {
d7d87535 672
4e781c7b 673 return;
674 }
0d5d12bd 675
4e781c7b 676 // What is the expected result based on this grade?
0d5d12bd 677 if ($deleted) {
4e781c7b 678 // Grade being deleted, so only change could be to make it incomplete
0d5d12bd 679 $possibleresult = COMPLETION_INCOMPLETE;
4e781c7b 680 } else {
0d5d12bd 681 $possibleresult = $this->internal_get_grade_state($item, $grade);
4e781c7b 682 }
0d5d12bd 683
4e781c7b 684 // OK, let's update state based on this
0d5d12bd 685 $this->update_state($cm, $possibleresult, $grade->userid);
4e781c7b 686 }
0d5d12bd 687
4e781c7b 688 /**
689 * Calculates the completion state that would result from a graded item
690 * (where grade-based completion is turned on) based on the actual grade
691 * and settings.
692 * <p>
693 * (Internal function. Not private, so we can unit-test it.)
694 *
91537a88 695 * @param grade_item $item
696 * @param grade_grade $grade
4e781c7b 697 * @return int Completion state e.g. COMPLETION_INCOMPLETE
698 */
91537a88 699 function internal_get_grade_state($item, $grade) {
0d5d12bd 700 if (!$grade) {
4e781c7b 701 return COMPLETION_INCOMPLETE;
702 }
703 // Conditions to show pass/fail:
704 // a) Grade has pass mark (default is 0.00000 which is boolean true so be careful)
705 // b) Grade is visible (neither hidden nor hidden-until)
0d5d12bd 706 if ($item->gradepass && $item->gradepass > 0.000009 && !$item->hidden) {
4e781c7b 707 // Use final grade if set otherwise raw grade
0d5d12bd 708 $score = !is_null($grade->finalgrade) ? $grade->finalgrade : $grade->rawgrade;
709
4e781c7b 710 // We are displaying and tracking pass/fail
0d5d12bd 711 if ($score >= $item->gradepass) {
4e781c7b 712 return COMPLETION_COMPLETE_PASS;
713 } else {
714 return COMPLETION_COMPLETE_FAIL;
715 }
716 } else {
717 // Not displaying pass/fail, but we know grade exists b/c we got here
718 return COMPLETION_COMPLETE;
719 }
720 }
0d5d12bd 721
4e781c7b 722 /**
4e781c7b 723 * This is to be used only for system errors (things that shouldn't happen)
724 * and not user-level errors.
725 *
726 * @param string $error Error string (will not be displayed to user unless
727 * debugging is enabled)
82bd6a5e 728 * @throws moodle_exception Exception with the error string as debug info
4e781c7b 729 */
730 function internal_systemerror($error) {
731 global $CFG;
82bd6a5e 732 throw new moodle_exception('err_system','completion',
733 $CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
734 }
d7d87535 735
82bd6a5e 736 /** For testing only. Wipes information cached in user session. */
737 static function wipe_session_cache() {
738 global $SESSION;
739 unset($SESSION->completioncache);
740 unset($SESSION->completioncacheuserid);
4e781c7b 741 }
742}
743
744
745?>