forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
completionlib.php
1821 lines (1593 loc) · 69.6 KB
/
completionlib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Contains classes, functions and constants used during the tracking
* of activity completion for users.
*
* Completion top-level options (admin setting enablecompletion)
*
* @package core_completion
* @category completion
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
use core_completion\activity_custom_completion;
use core_courseformat\base as course_format;
defined('MOODLE_INTERNAL') || die();
/**
* Include the required completion libraries
*/
require_once $CFG->dirroot.'/completion/completion_aggregation.php';
require_once $CFG->dirroot.'/completion/criteria/completion_criteria.php';
require_once $CFG->dirroot.'/completion/completion_completion.php';
require_once $CFG->dirroot.'/completion/completion_criteria_completion.php';
/**
* The completion system is enabled in this site/course
*/
define('COMPLETION_ENABLED', 1);
/**
* The completion system is not enabled in this site/course
*/
define('COMPLETION_DISABLED', 0);
/**
* Completion tracking is disabled for this activity
* This is a completion tracking option per-activity (course_modules/completion)
*/
define('COMPLETION_TRACKING_NONE', 0);
/**
* Manual completion tracking (user ticks box) is enabled for this activity
* This is a completion tracking option per-activity (course_modules/completion)
*/
define('COMPLETION_TRACKING_MANUAL', 1);
/**
* Automatic completion tracking (system ticks box) is enabled for this activity
* This is a completion tracking option per-activity (course_modules/completion)
*/
define('COMPLETION_TRACKING_AUTOMATIC', 2);
/**
* The user has not completed this activity.
* This is a completion state value (course_modules_completion/completionstate)
*/
define('COMPLETION_INCOMPLETE', 0);
/**
* The user has completed this activity. It is not specified whether they have
* passed or failed it.
* This is a completion state value (course_modules_completion/completionstate)
*/
define('COMPLETION_COMPLETE', 1);
/**
* The user has completed this activity with a grade above the pass mark.
* This is a completion state value (course_modules_completion/completionstate)
*/
define('COMPLETION_COMPLETE_PASS', 2);
/**
* The user has completed this activity but their grade is less than the pass mark
* This is a completion state value (course_modules_completion/completionstate)
*/
define('COMPLETION_COMPLETE_FAIL', 3);
/**
* Indicates that the user has received a failing grade for a hidden grade item.
*/
define('COMPLETION_COMPLETE_FAIL_HIDDEN', 4);
/**
* The effect of this change to completion status is unknown.
* A completion effect changes (used only in update_state)
*/
define('COMPLETION_UNKNOWN', -1);
/**
* The user's grade has changed, so their new state might be
* COMPLETION_COMPLETE_PASS or COMPLETION_COMPLETE_FAIL.
* A completion effect changes (used only in update_state)
*/
define('COMPLETION_GRADECHANGE', -2);
/**
* User must view this activity.
* Whether view is required to create an activity (course_modules/completionview)
*/
define('COMPLETION_VIEW_REQUIRED', 1);
/**
* User does not need to view this activity
* Whether view is required to create an activity (course_modules/completionview)
*/
define('COMPLETION_VIEW_NOT_REQUIRED', 0);
/**
* User has viewed this activity.
* Completion viewed state (course_modules_completion/viewed)
*/
define('COMPLETION_VIEWED', 1);
/**
* User has not viewed this activity.
* Completion viewed state (course_modules_completion/viewed)
*/
define('COMPLETION_NOT_VIEWED', 0);
/**
* Completion details should be ORed together and you should return false if
* none apply.
*/
define('COMPLETION_OR', false);
/**
* Completion details should be ANDed together and you should return true if
* none apply
*/
define('COMPLETION_AND', true);
/**
* Course completion criteria aggregation method.
*/
define('COMPLETION_AGGREGATION_ALL', 1);
/**
* Course completion criteria aggregation method.
*/
define('COMPLETION_AGGREGATION_ANY', 2);
/**
* Completion conditions will be displayed to user.
*/
define('COMPLETION_SHOW_CONDITIONS', 1);
/**
* Completion conditions will be hidden from user.
*/
define('COMPLETION_HIDE_CONDITIONS', 0);
/**
* Utility function for checking if the logged in user can view
* another's completion data for a particular course
*
* @access public
* @param int $userid Completion data's owner
* @param mixed $course Course object or Course ID (optional)
* @return boolean
*/
function completion_can_view_data($userid, $course = null) {
global $USER;
if (!isloggedin()) {
return false;
}
if (!is_object($course)) {
$cid = $course;
$course = new stdClass();
$course->id = $cid;
}
// Check if this is the site course
if ($course->id == SITEID) {
$course = null;
}
// Check if completion is enabled
if ($course) {
$cinfo = new completion_info($course);
if (!$cinfo->is_enabled()) {
return false;
}
} else {
if (!completion_info::is_enabled_for_site()) {
return false;
}
}
// Is own user's data?
if ($USER->id == $userid) {
return true;
}
// Check capabilities
$personalcontext = context_user::instance($userid);
if (has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)) {
return true;
} elseif (has_capability('report/completion:view', $personalcontext)) {
return true;
}
if ($course->id) {
$coursecontext = context_course::instance($course->id);
} else {
$coursecontext = context_system::instance();
}
if (has_capability('report/completion:view', $coursecontext)) {
return true;
}
return false;
}
/**
* Class represents completion information for a course.
*
* Does not contain any data, so you can safely construct it multiple times
* without causing any problems.
*
* @package core
* @category completion
* @copyright 2008 Sam Marshall
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class completion_info {
/* @var stdClass Course object passed during construction */
private $course;
/* @var int Course id */
public $course_id;
/* @var array Completion criteria {@link completion_info::get_criteria()} */
private $criteria;
/**
* Return array of aggregation methods
* @return array
*/
public static function get_aggregation_methods() {
return array(
COMPLETION_AGGREGATION_ALL => get_string('all'),
COMPLETION_AGGREGATION_ANY => get_string('any', 'completion'),
);
}
/**
* Constructs with course details.
*
* When instantiating a new completion info object you must provide a course
* object with at least id, and enablecompletion properties. Property
* cacherev is needed if you check completion of the current user since
* it is used for cache validation.
*
* @param stdClass $course Moodle course object.
*/
public function __construct($course) {
$this->course = $course;
$this->course_id = $course->id;
}
/**
* Determines whether completion is enabled across entire site.
*
* @return bool COMPLETION_ENABLED (true) if completion is enabled for the site,
* COMPLETION_DISABLED (false) if it's complete
*/
public static function is_enabled_for_site() {
global $CFG;
return !empty($CFG->enablecompletion);
}
/**
* Checks whether completion is enabled in a particular course and possibly
* activity.
*
* @param stdClass|cm_info $cm Course-module object. If not specified, returns the course
* completion enable state.
* @return mixed COMPLETION_ENABLED or COMPLETION_DISABLED (==0) in the case of
* site and course; COMPLETION_TRACKING_MANUAL, _AUTOMATIC or _NONE (==0)
* for a course-module.
*/
public function is_enabled($cm = null) {
global $CFG, $DB;
// First check global completion
if (!isset($CFG->enablecompletion) || $CFG->enablecompletion == COMPLETION_DISABLED) {
return COMPLETION_DISABLED;
}
// Load data if we do not have enough
if (!isset($this->course->enablecompletion)) {
$this->course = get_course($this->course_id);
}
// Check course completion
if ($this->course->enablecompletion == COMPLETION_DISABLED) {
return COMPLETION_DISABLED;
}
// If there was no $cm and we got this far, then it's enabled
if (!$cm) {
return COMPLETION_ENABLED;
}
// Return course-module completion value
return $cm->completion;
}
/**
* @deprecated since Moodle 2.0 - Use display_help_icon instead.
*/
public function print_help_icon() {
throw new coding_exception(__FUNCTION__ . '() has been removed.');
}
/**
* @deprecated since Moodle 4.0 - The 'Your progress' info isn't displayed any more.
*/
public function display_help_icon() {
throw new coding_exception(__FUNCTION__ . '() has been removed.');
}
/**
* Get a course completion for a user
*
* @param int $user_id User id
* @param int $criteriatype Specific criteria type to return
* @return bool|completion_criteria_completion returns false on fail
*/
public function get_completion($user_id, $criteriatype) {
$completions = $this->get_completions($user_id, $criteriatype);
if (empty($completions)) {
return false;
} elseif (count($completions) > 1) {
throw new \moodle_exception('multipleselfcompletioncriteria', 'completion');
}
return $completions[0];
}
/**
* Get all course criteria's completion objects for a user
*
* @param int $user_id User id
* @param int $criteriatype Specific criteria type to return (optional)
* @return array
*/
public function get_completions($user_id, $criteriatype = null) {
$criteria = $this->get_criteria($criteriatype);
$completions = array();
foreach ($criteria as $criterion) {
$params = array(
'course' => $this->course_id,
'userid' => $user_id,
'criteriaid' => $criterion->id
);
$completion = new completion_criteria_completion($params);
$completion->attach_criteria($criterion);
$completions[] = $completion;
}
return $completions;
}
/**
* Get completion object for a user and a criteria
*
* @param int $user_id User id
* @param completion_criteria $criteria Criteria object
* @return completion_criteria_completion
*/
public function get_user_completion($user_id, $criteria) {
$params = array(
'course' => $this->course_id,
'userid' => $user_id,
'criteriaid' => $criteria->id,
);
$completion = new completion_criteria_completion($params);
return $completion;
}
/**
* Check if course has completion criteria set
*
* @return bool Returns true if there are criteria
*/
public function has_criteria() {
$criteria = $this->get_criteria();
return (bool) count($criteria);
}
/**
* Get course completion criteria
*
* @param int $criteriatype Specific criteria type to return (optional)
*/
public function get_criteria($criteriatype = null) {
// Fill cache if empty
if (!is_array($this->criteria)) {
global $DB;
$params = array(
'course' => $this->course->id
);
// Load criteria from database
$records = (array)$DB->get_records('course_completion_criteria', $params);
// Order records so activities are in the same order as they appear on the course view page.
if ($records) {
$activitiesorder = array_keys(get_fast_modinfo($this->course)->get_cms());
usort($records, function ($a, $b) use ($activitiesorder) {
$aidx = ($a->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
array_search($a->moduleinstance, $activitiesorder) : false;
$bidx = ($b->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) ?
array_search($b->moduleinstance, $activitiesorder) : false;
if ($aidx === false || $bidx === false || $aidx == $bidx) {
return 0;
}
return ($aidx < $bidx) ? -1 : 1;
});
}
// Build array of criteria objects
$this->criteria = array();
foreach ($records as $record) {
$this->criteria[$record->id] = completion_criteria::factory((array)$record);
}
}
// If after all criteria
if ($criteriatype === null) {
return $this->criteria;
}
// If we are only after a specific criteria type
$criteria = array();
foreach ($this->criteria as $criterion) {
if ($criterion->criteriatype != $criteriatype) {
continue;
}
$criteria[$criterion->id] = $criterion;
}
return $criteria;
}
/**
* Get aggregation method
*
* @param int $criteriatype If none supplied, get overall aggregation method (optional)
* @return int One of COMPLETION_AGGREGATION_ALL or COMPLETION_AGGREGATION_ANY
*/
public function get_aggregation_method($criteriatype = null) {
$params = array(
'course' => $this->course_id,
'criteriatype' => $criteriatype
);
$aggregation = new completion_aggregation($params);
if (!$aggregation->id) {
$aggregation->method = COMPLETION_AGGREGATION_ALL;
}
return $aggregation->method;
}
/**
* @deprecated since Moodle 2.8 MDL-46290.
*/
public function get_incomplete_criteria() {
throw new coding_exception('completion_info->get_incomplete_criteria() is removed.');
}
/**
* Clear old course completion criteria
*/
public function clear_criteria() {
global $DB;
// Remove completion criteria records for the course itself, and any records that refer to the course.
$select = 'course = :course OR (criteriatype = :type AND courseinstance = :courseinstance)';
$params = [
'course' => $this->course_id,
'type' => COMPLETION_CRITERIA_TYPE_COURSE,
'courseinstance' => $this->course_id,
];
$DB->delete_records_select('course_completion_criteria', $select, $params);
$DB->delete_records('course_completion_aggr_methd', array('course' => $this->course_id));
$this->delete_course_completion_data();
}
/**
* Has the supplied user completed this course
*
* @param int $user_id User's id
* @return boolean
*/
public function is_course_complete($user_id) {
$params = array(
'userid' => $user_id,
'course' => $this->course_id
);
$ccompletion = new completion_completion($params);
return $ccompletion->is_complete();
}
/**
* Check whether the supplied user can override the activity completion statuses within the current course.
*
* @param stdClass $user The user object.
* @return bool True if the user can override, false otherwise.
*/
public function user_can_override_completion($user) {
return has_capability('moodle/course:overridecompletion', context_course::instance($this->course_id), $user);
}
/**
* Updates (if necessary) the completion state of activity $cm for the given
* user.
*
* For manual completion, this function is called when completion is toggled
* with $possibleresult set to the target state.
*
* For automatic completion, this function should be called every time a module
* does something which might influence a user's completion state. For example,
* if a forum provides options for marking itself 'completed' once a user makes
* N posts, this function should be called every time a user makes a new post.
* [After the post has been saved to the database]. When calling, you do not
* need to pass in the new completion state. Instead this function carries out completion
* calculation by checking grades and viewed state itself, and calling the involved module
* via mod_{modulename}\\completion\\custom_completion::get_overall_completion_state() to
* check module-specific conditions.
*
* @param stdClass|cm_info $cm Course-module
* @param int $possibleresult Expected completion result. If the event that
* has just occurred (e.g. add post) can only result in making the activity
* complete when it wasn't before, use COMPLETION_COMPLETE. If the event that
* has just occurred (e.g. delete post) can only result in making the activity
* not complete when it was previously complete, use COMPLETION_INCOMPLETE.
* Otherwise use COMPLETION_UNKNOWN. Setting this value to something other than
* COMPLETION_UNKNOWN significantly improves performance because it will abandon
* processing early if the user's completion state already matches the expected
* result. For manual events, COMPLETION_COMPLETE or COMPLETION_INCOMPLETE
* must be used; these directly set the specified state.
* @param int $userid User ID to be updated. Default 0 = current user
* @param bool $override Whether manually overriding the existing completion state.
* @param bool $isbulkupdate If bulk grade update is happening.
* @return void
* @throws moodle_exception if trying to override without permission.
*/
public function update_state($cm, $possibleresult=COMPLETION_UNKNOWN, $userid=0,
$override = false, $isbulkupdate = false) {
global $USER;
// Do nothing if completion is not enabled for that activity
if (!$this->is_enabled($cm)) {
return;
}
// If we're processing an override and the current user isn't allowed to do so, then throw an exception.
if ($override) {
if (!$this->user_can_override_completion($USER)) {
throw new required_capability_exception(context_course::instance($this->course_id),
'moodle/course:overridecompletion', 'nopermission', '');
}
}
// Default to current user if one is not provided.
if ($userid == 0) {
$userid = $USER->id;
}
// Delete the cm's cached completion data for this user if automatic completion is enabled.
// This ensures any changes to the status of individual completion conditions in the activity will be fetched.
if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC) {
$completioncache = cache::make('core', 'completion');
$completionkey = $userid . '_' . $this->course->id;
$completiondata = $completioncache->get($completionkey);
if ($completiondata !== false) {
unset($completiondata[$cm->id]);
$completioncache->set($completionkey, $completiondata);
}
}
// Get current value of completion state and do nothing if it's same as
// the possible result of this change. If the change is to COMPLETE and the
// current value is one of the COMPLETE_xx subtypes, ignore that as well
$current = $this->get_data($cm, false, $userid);
if ($possibleresult == $current->completionstate ||
($possibleresult == COMPLETION_COMPLETE &&
($current->completionstate == COMPLETION_COMPLETE_PASS ||
$current->completionstate == COMPLETION_COMPLETE_FAIL))) {
return;
}
// The activity completion alters the course state cache for this particular user.
$course = get_course($cm->course);
if ($course) {
course_format::session_cache_reset($course);
}
// For auto tracking, if the status is overridden to 'COMPLETION_COMPLETE', then disallow further changes,
// unless processing another override.
// Basically, we want those activities which have been overridden to COMPLETE to hold state, and those which have been
// overridden to INCOMPLETE to still be processed by normal completion triggers.
if ($cm->completion == COMPLETION_TRACKING_AUTOMATIC && !is_null($current->overrideby)
&& $current->completionstate == COMPLETION_COMPLETE && !$override) {
return;
}
// For manual tracking, or if overriding the completion state, we set the state directly.
if ($cm->completion == COMPLETION_TRACKING_MANUAL || $override) {
switch($possibleresult) {
case COMPLETION_COMPLETE:
case COMPLETION_INCOMPLETE:
$newstate = $possibleresult;
break;
default:
$this->internal_systemerror("Unexpected manual completion state for {$cm->id}: $possibleresult");
}
} else {
$newstate = $this->internal_get_state($cm, $userid, $current);
}
// If the overall completion state has changed, update it in the cache.
if ($newstate != $current->completionstate) {
$current->completionstate = $newstate;
$current->timemodified = time();
$current->overrideby = $override ? $USER->id : null;
$this->internal_set_data($cm, $current, $isbulkupdate);
}
}
/**
* Calculates the completion state for an activity and user.
*
* Internal function. Not private, so we can unit-test it.
*
* @param stdClass|cm_info $cm Activity
* @param int $userid ID of user
* @param stdClass $current Previous completion information from database
* @return mixed
*/
public function internal_get_state($cm, $userid, $current) {
global $USER, $DB;
// Get user ID
if (!$userid) {
$userid = $USER->id;
}
$newstate = COMPLETION_COMPLETE;
if ($cm instanceof stdClass) {
// Modname hopefully is provided in $cm but just in case it isn't, let's grab it.
if (!isset($cm->modname)) {
$cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
}
// Some functions call this method and pass $cm as an object with ID only. Make sure course is set as well.
if (!isset($cm->course)) {
$cm->course = $this->course_id;
}
}
// Make sure we're using a cm_info object.
$cminfo = cm_info::create($cm, $userid);
$completionstate = $this->get_core_completion_state($cminfo, $userid);
if (plugin_supports('mod', $cminfo->modname, FEATURE_COMPLETION_HAS_RULES)) {
$cmcompletionclass = activity_custom_completion::get_cm_completion_class($cminfo->modname);
if ($cmcompletionclass) {
/** @var activity_custom_completion $cmcompletion */
$cmcompletion = new $cmcompletionclass($cminfo, $userid, $completionstate);
$customstate = $cmcompletion->get_overall_completion_state();
if ($customstate == COMPLETION_INCOMPLETE) {
return $customstate;
}
$completionstate[] = $customstate;
}
}
if ($completionstate) {
// We have allowed the plugins to do it's thing and run their own checks.
// We have now reached a state where we need to AND all the calculated results.
// Preference for COMPLETION_COMPLETE_PASS over COMPLETION_COMPLETE for proper indication in reports.
$newstate = array_reduce($completionstate, function($carry, $value) {
if (in_array(COMPLETION_INCOMPLETE, [$carry, $value])) {
return COMPLETION_INCOMPLETE;
} else if (in_array(COMPLETION_COMPLETE_FAIL, [$carry, $value])) {
return COMPLETION_COMPLETE_FAIL;
} else {
return in_array(COMPLETION_COMPLETE_PASS, [$carry, $value]) ? COMPLETION_COMPLETE_PASS : $value;
}
}, COMPLETION_COMPLETE);
}
return $newstate;
}
/**
* Fetches the completion state for an activity completion's require grade completion requirement.
*
* @param cm_info $cm The course module information.
* @param int $userid The user ID.
* @return int The completion state.
*/
public function get_grade_completion(cm_info $cm, int $userid): int {
global $CFG;
require_once($CFG->libdir . '/gradelib.php');
$item = grade_item::fetch([
'courseid' => $cm->course,
'itemtype' => 'mod',
'itemmodule' => $cm->modname,
'iteminstance' => $cm->instance,
'itemnumber' => $cm->completiongradeitemnumber
]);
if ($item) {
// Fetch 'grades' (will be one or none).
$grades = grade_grade::fetch_users_grades($item, [$userid], false);
if (empty($grades)) {
// No grade for user.
return COMPLETION_INCOMPLETE;
}
if (count($grades) > 1) {
$this->internal_systemerror("Unexpected result: multiple grades for
item '{$item->id}', user '{$userid}'");
}
$returnpassfail = !empty($cm->completionpassgrade);
return self::internal_get_grade_state($item, reset($grades), $returnpassfail);
}
return COMPLETION_INCOMPLETE;
}
/**
* Marks a module as viewed.
*
* Should be called whenever a module is 'viewed' (it is up to the module how to
* determine that). Has no effect if viewing is not set as a completion condition.
*
* Note that this function must be called before you print the page header because
* it is possible that the navigation block may depend on it. If you call it after
* printing the header, it shows a developer debug warning.
*
* @param stdClass|cm_info $cm Activity
* @param int $userid User ID or 0 (default) for current user
* @return void
*/
public function set_module_viewed($cm, $userid=0) {
global $PAGE;
if ($PAGE->headerprinted) {
debugging('set_module_viewed must be called before header is printed',
DEBUG_DEVELOPER);
}
// Don't do anything if view condition is not turned on
if ($cm->completionview == COMPLETION_VIEW_NOT_REQUIRED || !$this->is_enabled($cm)) {
return;
}
// Get current completion state
$data = $this->get_data($cm, false, $userid);
// If we already viewed it, don't do anything unless the completion status is overridden.
// If the completion status is overridden, then we need to allow this 'view' to trigger automatic completion again.
if ($data->viewed == COMPLETION_VIEWED && empty($data->overrideby)) {
return;
}
// OK, change state, save it, and update completion
$data->viewed = COMPLETION_VIEWED;
$this->internal_set_data($cm, $data);
$this->update_state($cm, COMPLETION_COMPLETE, $userid);
}
/**
* Determines how much completion data exists for an activity. This is used when
* deciding whether completion information should be 'locked' in the module
* editing form.
*
* @param cm_info $cm Activity
* @return int The number of users who have completion data stored for this
* activity, 0 if none
*/
public function count_user_data($cm) {
global $DB;
return $DB->get_field_sql("
SELECT
COUNT(1)
FROM
{course_modules_completion}
WHERE
coursemoduleid=? AND completionstate<>0", array($cm->id));
}
/**
* Determines how much course completion data exists for a course. This is used when
* deciding whether completion information should be 'locked' in the completion
* settings form and activity completion settings.
*
* @param int $user_id Optionally only get course completion data for a single user
* @return int The number of users who have completion data stored for this
* course, 0 if none
*/
public function count_course_user_data($user_id = null) {
global $DB;
$sql = '
SELECT
COUNT(1)
FROM
{course_completion_crit_compl}
WHERE
course = ?
';
$params = array($this->course_id);
// Limit data to a single user if an ID is supplied
if ($user_id) {
$sql .= ' AND userid = ?';
$params[] = $user_id;
}
return $DB->get_field_sql($sql, $params);
}
/**
* Check if this course's completion criteria should be locked
*
* @return boolean
*/
public function is_course_locked() {
return (bool) $this->count_course_user_data();
}
/**
* Deletes all course completion completion data.
*
* Intended to be used when unlocking completion criteria settings.
*/
public function delete_course_completion_data() {
global $DB;
$DB->delete_records('course_completions', array('course' => $this->course_id));
$DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id));
// Difficult to find affected users, just purge all completion cache.
cache::make('core', 'completion')->purge();
cache::make('core', 'coursecompletion')->purge();
}
/**
* Deletes all activity and course completion data for an entire course
* (the below delete_all_state function does this for a single activity).
*
* Used by course reset page.
*/
public function delete_all_completion_data() {
global $DB;
// Delete from database.
$DB->delete_records_select('course_modules_completion',
'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
array($this->course_id));
$DB->delete_records_select('course_modules_viewed',
'coursemoduleid IN (SELECT id FROM {course_modules} WHERE course=?)',
[$this->course_id]);
// Wipe course completion data too.
$this->delete_course_completion_data();
}
/**
* Deletes completion state related to an activity for all users.
*
* Intended for use only when the activity itself is deleted.
*
* @param stdClass|cm_info $cm Activity
*/
public function delete_all_state($cm) {
global $DB;
// Delete from database
$DB->delete_records('course_modules_completion', array('coursemoduleid'=>$cm->id));
// Check if there is an associated course completion criteria
$criteria = $this->get_criteria(COMPLETION_CRITERIA_TYPE_ACTIVITY);
$acriteria = false;
foreach ($criteria as $criterion) {
if ($criterion->moduleinstance == $cm->id) {
$acriteria = $criterion;
break;
}
}
if ($acriteria) {
// Delete all criteria completions relating to this activity
$DB->delete_records('course_completion_crit_compl', array('course' => $this->course_id, 'criteriaid' => $acriteria->id));
$DB->delete_records('course_completions', array('course' => $this->course_id));
}
// Difficult to find affected users, just purge all completion cache.
cache::make('core', 'completion')->purge();
cache::make('core', 'coursecompletion')->purge();
}
/**
* Recalculates completion state related to an activity for all users.
*
* Intended for use if completion conditions change. (This should be avoided
* as it may cause some things to become incomplete when they were previously
* complete, with the effect - for example - of hiding a later activity that
* was previously available.)
*
* Resetting state of manual tickbox has same result as deleting state for
* it.
*
* @param stdClass|cm_info $cm Activity
*/
public function reset_all_state($cm) {
global $DB;
if ($cm->completion == COMPLETION_TRACKING_MANUAL) {
$this->delete_all_state($cm);
return;
}
// Get current list of users with completion state
$rs = $DB->get_recordset('course_modules_completion', array('coursemoduleid'=>$cm->id), '', 'userid');
$keepusers = array();
foreach ($rs as $rec) {
$keepusers[] = $rec->userid;
}
$rs->close();
// Delete all existing state.
$this->delete_all_state($cm);
// Merge this with list of planned users (according to roles)
$trackedusers = $this->get_tracked_users();
foreach ($trackedusers as $trackeduser) {
$keepusers[] = $trackeduser->id;
}
$keepusers = array_unique($keepusers);
// Recalculate state for each kept user
foreach ($keepusers as $keepuser) {
$this->update_state($cm, COMPLETION_UNKNOWN, $keepuser);
}
}
/**
* Obtains completion data for a particular activity and user (from the
* completion cache if available, or by SQL query)
*
* @param stdClass|cm_info $cm Activity; only required field is ->id
* @param bool $wholecourse If true (default false) then, when necessary to
* fill the cache, retrieves information from the entire course not just for
* this one activity
* @param int $userid User ID or 0 (default) for current user
* @param mixed $unused This parameter has been deprecated since 4.0 and should not be used anymore.
* @return object Completion data. Record from course_modules_completion plus other completion statuses such as
* - Completion status for 'must-receive-grade' completion rule.
* - Custom completion statuses defined by the activity module plugin.
*/
public function get_data($cm, $wholecourse = false, $userid = 0, $unused = null) {
global $USER, $DB;