forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.php
1753 lines (1550 loc) · 61.9 KB
/
lib.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/>.
/**
* Standard library of functions and constants for lesson
*
* @package mod_lesson
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
**/
defined('MOODLE_INTERNAL') || die();
// Event types.
define('LESSON_EVENT_TYPE_OPEN', 'open');
define('LESSON_EVENT_TYPE_CLOSE', 'close');
require_once(__DIR__ . '/deprecatedlib.php');
/* Do not include any libraries here! */
/**
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will create a new instance and return the id number
* of the new instance.
*
* @global object
* @global object
* @param object $lesson Lesson post data from the form
* @return int
**/
function lesson_add_instance($data, $mform) {
global $DB;
$cmid = $data->coursemodule;
$draftitemid = $data->mediafile;
$context = context_module::instance($cmid);
lesson_process_pre_save($data);
unset($data->mediafile);
$lessonid = $DB->insert_record("lesson", $data);
$data->id = $lessonid;
lesson_update_media_file($lessonid, $context, $draftitemid);
lesson_process_post_save($data);
lesson_grade_item_update($data);
return $lessonid;
}
/**
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will update an existing instance with new data.
*
* @global object
* @param object $lesson Lesson post data from the form
* @return boolean
**/
function lesson_update_instance($data, $mform) {
global $DB;
$data->id = $data->instance;
$cmid = $data->coursemodule;
$draftitemid = $data->mediafile;
$context = context_module::instance($cmid);
lesson_process_pre_save($data);
unset($data->mediafile);
$DB->update_record("lesson", $data);
lesson_update_media_file($data->id, $context, $draftitemid);
lesson_process_post_save($data);
// update grade item definition
lesson_grade_item_update($data);
// update grades - TODO: do it only when grading style changes
lesson_update_grades($data, 0, false);
return true;
}
/**
* This function updates the events associated to the lesson.
* If $override is non-zero, then it updates only the events
* associated with the specified override.
*
* @uses LESSON_MAX_EVENT_LENGTH
* @param object $lesson the lesson object.
* @param object $override (optional) limit to a specific override
*/
function lesson_update_events($lesson, $override = null) {
global $CFG, $DB;
require_once($CFG->dirroot . '/mod/lesson/locallib.php');
require_once($CFG->dirroot . '/calendar/lib.php');
// Load the old events relating to this lesson.
$conds = array('modulename' => 'lesson',
'instance' => $lesson->id);
if (!empty($override)) {
// Only load events for this override.
if (isset($override->userid)) {
$conds['userid'] = $override->userid;
} else {
$conds['groupid'] = $override->groupid;
}
}
$oldevents = $DB->get_records('event', $conds, 'id ASC');
// Now make a to-do list of all that needs to be updated.
if (empty($override)) {
// We are updating the primary settings for the lesson, so we need to add all the overrides.
$overrides = $DB->get_records('lesson_overrides', array('lessonid' => $lesson->id), 'id ASC');
// It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
// list contains the original (non-override) event for the module. If this is not included
// the logic below will end up updating the wrong row when we try to reconcile this $overrides
// list against the $oldevents list.
array_unshift($overrides, new stdClass());
} else {
// Just do the one override.
$overrides = array($override);
}
// Get group override priorities.
$grouppriorities = lesson_get_group_override_priorities($lesson->id);
foreach ($overrides as $current) {
$groupid = isset($current->groupid) ? $current->groupid : 0;
$userid = isset($current->userid) ? $current->userid : 0;
$available = isset($current->available) ? $current->available : $lesson->available;
$deadline = isset($current->deadline) ? $current->deadline : $lesson->deadline;
// Only add open/close events for an override if they differ from the lesson default.
$addopen = empty($current->id) || !empty($current->available);
$addclose = empty($current->id) || !empty($current->deadline);
if (!empty($lesson->coursemodule)) {
$cmid = $lesson->coursemodule;
} else {
$cmid = get_coursemodule_from_instance('lesson', $lesson->id, $lesson->course)->id;
}
$event = new stdClass();
$event->type = !$deadline ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
$event->description = format_module_intro('lesson', $lesson, $cmid, false);
$event->format = FORMAT_HTML;
// Events module won't show user events when the courseid is nonzero.
$event->courseid = ($userid) ? 0 : $lesson->course;
$event->groupid = $groupid;
$event->userid = $userid;
$event->modulename = 'lesson';
$event->instance = $lesson->id;
$event->timestart = $available;
$event->timeduration = max($deadline - $available, 0);
$event->timesort = $available;
$event->visible = instance_is_visible('lesson', $lesson);
$event->eventtype = LESSON_EVENT_TYPE_OPEN;
$event->priority = null;
// Determine the event name and priority.
if ($groupid) {
// Group override event.
$params = new stdClass();
$params->lesson = $lesson->name;
$params->group = groups_get_group_name($groupid);
if ($params->group === false) {
// Group doesn't exist, just skip it.
continue;
}
$eventname = get_string('overridegroupeventname', 'lesson', $params);
// Set group override priority.
if ($grouppriorities !== null) {
$openpriorities = $grouppriorities['open'];
if (isset($openpriorities[$available])) {
$event->priority = $openpriorities[$available];
}
}
} else if ($userid) {
// User override event.
$params = new stdClass();
$params->lesson = $lesson->name;
$eventname = get_string('overrideusereventname', 'lesson', $params);
// Set user override priority.
$event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
} else {
// The parent event.
$eventname = $lesson->name;
}
if ($addopen or $addclose) {
// Separate start and end events.
$event->timeduration = 0;
if ($available && $addopen) {
if ($oldevent = array_shift($oldevents)) {
$event->id = $oldevent->id;
} else {
unset($event->id);
}
$event->name = get_string('lessoneventopens', 'lesson', $eventname);
// The method calendar_event::create will reuse a db record if the id field is set.
calendar_event::create($event, false);
}
if ($deadline && $addclose) {
if ($oldevent = array_shift($oldevents)) {
$event->id = $oldevent->id;
} else {
unset($event->id);
}
$event->type = CALENDAR_EVENT_TYPE_ACTION;
$event->name = get_string('lessoneventcloses', 'lesson', $eventname);
$event->timestart = $deadline;
$event->timesort = $deadline;
$event->eventtype = LESSON_EVENT_TYPE_CLOSE;
if ($groupid && $grouppriorities !== null) {
$closepriorities = $grouppriorities['close'];
if (isset($closepriorities[$deadline])) {
$event->priority = $closepriorities[$deadline];
}
}
calendar_event::create($event, false);
}
}
}
// Delete any leftover events.
foreach ($oldevents as $badevent) {
$badevent = calendar_event::load($badevent);
$badevent->delete();
}
}
/**
* Calculates the priorities of timeopen and timeclose values for group overrides for a lesson.
*
* @param int $lessonid The lesson ID.
* @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
*/
function lesson_get_group_override_priorities($lessonid) {
global $DB;
// Fetch group overrides.
$where = 'lessonid = :lessonid AND groupid IS NOT NULL';
$params = ['lessonid' => $lessonid];
$overrides = $DB->get_records_select('lesson_overrides', $where, $params, '', 'id, groupid, available, deadline');
if (!$overrides) {
return null;
}
$grouptimeopen = [];
$grouptimeclose = [];
foreach ($overrides as $override) {
if ($override->available !== null && !in_array($override->available, $grouptimeopen)) {
$grouptimeopen[] = $override->available;
}
if ($override->deadline !== null && !in_array($override->deadline, $grouptimeclose)) {
$grouptimeclose[] = $override->deadline;
}
}
// Sort open times in ascending manner. The earlier open time gets higher priority.
sort($grouptimeopen);
// Set priorities.
$opengrouppriorities = [];
$openpriority = 1;
foreach ($grouptimeopen as $timeopen) {
$opengrouppriorities[$timeopen] = $openpriority++;
}
// Sort close times in descending manner. The later close time gets higher priority.
rsort($grouptimeclose);
// Set priorities.
$closegrouppriorities = [];
$closepriority = 1;
foreach ($grouptimeclose as $timeclose) {
$closegrouppriorities[$timeclose] = $closepriority++;
}
return [
'open' => $opengrouppriorities,
'close' => $closegrouppriorities
];
}
/**
* This standard function will check all instances of this module
* and make sure there are up-to-date events created for each of them.
* If courseid = 0, then every lesson event in the site is checked, else
* only lesson events belonging to the course specified are checked.
* This function is used, in its new format, by restore_refresh_events()
*
* @param int $courseid
* @param int|stdClass $instance Lesson module instance or ID.
* @param int|stdClass $cm Course module object or ID (not used in this module).
* @return bool
*/
function lesson_refresh_events($courseid = 0, $instance = null, $cm = null) {
global $DB;
// If we have instance information then we can just update the one event instead of updating all events.
if (isset($instance)) {
if (!is_object($instance)) {
$instance = $DB->get_record('lesson', array('id' => $instance), '*', MUST_EXIST);
}
lesson_update_events($instance);
return true;
}
if ($courseid == 0) {
if (!$lessons = $DB->get_records('lesson')) {
return true;
}
} else {
if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) {
return true;
}
}
foreach ($lessons as $lesson) {
lesson_update_events($lesson);
}
return true;
}
/**
* Given an ID of an instance of this module,
* this function will permanently delete the instance
* and any data that depends on it.
*
* @global object
* @param int $id
* @return bool
*/
function lesson_delete_instance($id) {
global $DB, $CFG;
require_once($CFG->dirroot . '/mod/lesson/locallib.php');
$lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST);
$lesson = new lesson($lesson);
return $lesson->delete();
}
/**
* Return a small object with summary information about what a
* user has done with a given particular instance of this module
* Used for user activity reports.
* $return->time = the time they did it
* $return->info = a short text description
*
* @global object
* @param object $course
* @param object $user
* @param object $mod
* @param object $lesson
* @return object
*/
function lesson_user_outline($course, $user, $mod, $lesson) {
global $CFG, $DB;
require_once("$CFG->libdir/gradelib.php");
$grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
$return = new stdClass();
if (empty($grades->items[0]->grades)) {
$return->info = get_string("nolessonattempts", "lesson");
} else {
$grade = reset($grades->items[0]->grades);
if (empty($grade->grade)) {
// Check to see if it an ungraded / incomplete attempt.
$sql = "SELECT *
FROM {lesson_timer}
WHERE lessonid = :lessonid
AND userid = :userid
ORDER BY starttime DESC";
$params = array('lessonid' => $lesson->id, 'userid' => $user->id);
if ($attempts = $DB->get_records_sql($sql, $params, 0, 1)) {
$attempt = reset($attempts);
if ($attempt->completed) {
$return->info = get_string("completed", "lesson");
} else {
$return->info = get_string("notyetcompleted", "lesson");
}
$return->time = $attempt->lessontime;
} else {
$return->info = get_string("nolessonattempts", "lesson");
}
} else {
if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
$return->info = get_string('gradenoun') . ': ' . $grade->str_long_grade;
} else {
$return->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
}
$return->time = grade_get_date_for_user_grade($grade, $user);
}
}
return $return;
}
/**
* Print a detailed representation of what a user has done with
* a given particular instance of this module, for user activity reports.
*
* @global object
* @param object $course
* @param object $user
* @param object $mod
* @param object $lesson
* @return bool
*/
function lesson_user_complete($course, $user, $mod, $lesson) {
global $DB, $OUTPUT, $CFG;
require_once("$CFG->libdir/gradelib.php");
$grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
// Display the grade and feedback.
if (empty($grades->items[0]->grades)) {
echo $OUTPUT->container(get_string("nolessonattempts", "lesson"));
} else {
$grade = reset($grades->items[0]->grades);
if (empty($grade->grade)) {
// Check to see if it an ungraded / incomplete attempt.
$sql = "SELECT *
FROM {lesson_timer}
WHERE lessonid = :lessonid
AND userid = :userid
ORDER by starttime desc";
$params = array('lessonid' => $lesson->id, 'userid' => $user->id);
if ($attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE)) {
if ($attempt->completed) {
$status = get_string("completed", "lesson");
} else {
$status = get_string("notyetcompleted", "lesson");
}
} else {
$status = get_string("nolessonattempts", "lesson");
}
} else {
if (!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
$status = get_string('gradenoun') . ': ' . $grade->str_long_grade;
} else {
$status = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
}
}
// Display the grade or lesson status if there isn't one.
echo $OUTPUT->container($status);
if ($grade->str_feedback &&
(!$grade->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id)))) {
echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
}
}
// Display the lesson progress.
// Attempt, pages viewed, questions answered, correct answers, time.
$params = array ("lessonid" => $lesson->id, "userid" => $user->id);
$attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
$branches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
if (!empty($attempts) or !empty($branches)) {
echo $OUTPUT->box_start();
$table = new html_table();
// Table Headings.
$table->head = array (get_string("attemptheader", "lesson"),
get_string("totalpagesviewedheader", "lesson"),
get_string("numberofpagesviewedheader", "lesson"),
get_string("numberofcorrectanswersheader", "lesson"),
get_string("time"));
$table->width = "100%";
$table->align = array ("center", "center", "center", "center", "center");
$table->size = array ("*", "*", "*", "*", "*");
$table->cellpadding = 2;
$table->cellspacing = 0;
$retry = 0;
$nquestions = 0;
$npages = 0;
$ncorrect = 0;
// Filter question pages (from lesson_attempts).
foreach ($attempts as $attempt) {
if ($attempt->retry == $retry) {
$npages++;
$nquestions++;
if ($attempt->correct) {
$ncorrect++;
}
$timeseen = $attempt->timeseen;
} else {
$table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
$retry++;
$nquestions = 1;
$npages = 1;
if ($attempt->correct) {
$ncorrect = 1;
} else {
$ncorrect = 0;
}
}
}
// Filter content pages (from lesson_branch).
foreach ($branches as $branch) {
if ($branch->retry == $retry) {
$npages++;
$timeseen = $branch->timeseen;
} else {
$table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
$retry++;
$npages = 1;
}
}
if ($npages > 0) {
$table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
}
echo html_writer::table($table);
echo $OUTPUT->box_end();
}
return true;
}
/**
* @deprecated since Moodle 3.3, when the block_course_overview block was removed.
*/
function lesson_print_overview() {
throw new coding_exception('lesson_print_overview() can not be used any more and is obsolete.');
}
/**
* Function to be run periodically according to the moodle cron
* This function searches for things that need to be done, such
* as sending out mail, toggling flags etc ...
* @global stdClass
* @return bool true
*/
function lesson_cron () {
global $CFG;
return true;
}
/**
* Return grade for given user or all users.
*
* @global stdClass
* @global object
* @param int $lessonid id of lesson
* @param int $userid optional user id, 0 means all users
* @return array array of grades, false if none
*/
function lesson_get_user_grades($lesson, $userid=0) {
global $CFG, $DB;
$params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id);
if (!empty($userid)) {
$params["userid"] = $userid;
$params["userid2"] = $userid;
$user = "AND u.id = :userid";
$fuser = "AND uu.id = :userid2";
}
else {
$user="";
$fuser="";
}
if ($lesson->retake) {
if ($lesson->usemaxgrade) {
$sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade
FROM {user} u, {lesson_grades} g
WHERE u.id = g.userid AND g.lessonid = :lessonid
$user
GROUP BY u.id";
} else {
$sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade
FROM {user} u, {lesson_grades} g
WHERE u.id = g.userid AND g.lessonid = :lessonid
$user
GROUP BY u.id";
}
unset($params['lessonid2']);
unset($params['userid2']);
} else {
// use only first attempts (with lowest id in lesson_grades table)
$firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted
FROM {user} uu, {lesson_grades} gg
WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2
$fuser
GROUP BY uu.id";
$sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade
FROM {user} u, {lesson_grades} g, ($firstonly) f
WHERE u.id = g.userid AND g.lessonid = :lessonid
AND g.id = f.firstcompleted AND g.userid=f.userid
$user";
}
return $DB->get_records_sql($sql, $params);
}
/**
* Update grades in central gradebook
*
* @category grade
* @param object $lesson
* @param int $userid specific user only, 0 means all
* @param bool $nullifnone
*/
function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
global $CFG, $DB;
require_once($CFG->libdir.'/gradelib.php');
if ($lesson->grade == 0 || $lesson->practice) {
lesson_grade_item_update($lesson);
} else if ($grades = lesson_get_user_grades($lesson, $userid)) {
lesson_grade_item_update($lesson, $grades);
} else if ($userid and $nullifnone) {
$grade = new stdClass();
$grade->userid = $userid;
$grade->rawgrade = null;
lesson_grade_item_update($lesson, $grade);
} else {
lesson_grade_item_update($lesson);
}
}
/**
* Create grade item for given lesson
*
* @category grade
* @uses GRADE_TYPE_VALUE
* @uses GRADE_TYPE_NONE
* @param object $lesson object with extra cmidnumber
* @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
* @return int 0 if ok, error code otherwise
*/
function lesson_grade_item_update($lesson, $grades=null) {
global $CFG;
if (!function_exists('grade_update')) { //workaround for buggy PHP versions
require_once($CFG->libdir.'/gradelib.php');
}
if (property_exists($lesson, 'cmidnumber')) { //it may not be always present
$params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber);
} else {
$params = array('itemname'=>$lesson->name);
}
if (!$lesson->practice and $lesson->grade > 0) {
$params['gradetype'] = GRADE_TYPE_VALUE;
$params['grademax'] = $lesson->grade;
$params['grademin'] = 0;
} else if (!$lesson->practice and $lesson->grade < 0) {
$params['gradetype'] = GRADE_TYPE_SCALE;
$params['scaleid'] = -$lesson->grade;
// Make sure current grade fetched correctly from $grades
$currentgrade = null;
if (!empty($grades)) {
if (is_array($grades)) {
$currentgrade = reset($grades);
} else {
$currentgrade = $grades;
}
}
// When converting a score to a scale, use scale's grade maximum to calculate it.
if (!empty($currentgrade) && $currentgrade->rawgrade !== null) {
$grade = grade_get_grades($lesson->course, 'mod', 'lesson', $lesson->id, $currentgrade->userid);
$params['grademax'] = reset($grade->items)->grademax;
}
} else {
$params['gradetype'] = GRADE_TYPE_NONE;
}
if ($grades === 'reset') {
$params['reset'] = true;
$grades = null;
} else if (!empty($grades)) {
// Need to calculate raw grade (Note: $grades has many forms)
if (is_object($grades)) {
$grades = array($grades->userid => $grades);
} else if (array_key_exists('userid', $grades)) {
$grades = array($grades['userid'] => $grades);
}
foreach ($grades as $key => $grade) {
if (!is_array($grade)) {
$grades[$key] = $grade = (array) $grade;
}
//check raw grade isnt null otherwise we erroneously insert a grade of 0
if ($grade['rawgrade'] !== null) {
$grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100);
} else {
//setting rawgrade to null just in case user is deleting a grade
$grades[$key]['rawgrade'] = null;
}
}
}
return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params);
}
/**
* List the actions that correspond to a view of this module.
* This is used by the participation report.
*
* Note: This is not used by new logging system. Event with
* crud = 'r' and edulevel = LEVEL_PARTICIPATING will
* be considered as view action.
*
* @return array
*/
function lesson_get_view_actions() {
return array('view','view all');
}
/**
* List the actions that correspond to a post of this module.
* This is used by the participation report.
*
* Note: This is not used by new logging system. Event with
* crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
* will be considered as post action.
*
* @return array
*/
function lesson_get_post_actions() {
return array('end','start');
}
/**
* Runs any processes that must run before
* a lesson insert/update
*
* @global object
* @param object $lesson Lesson form data
* @return void
**/
function lesson_process_pre_save(&$lesson) {
global $DB;
$lesson->timemodified = time();
if (empty($lesson->timelimit)) {
$lesson->timelimit = 0;
}
if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) {
$lesson->timespent = 0;
}
if (!isset($lesson->completed)) {
$lesson->completed = 0;
}
if (empty($lesson->gradebetterthan) or !is_numeric($lesson->gradebetterthan) or $lesson->gradebetterthan < 0) {
$lesson->gradebetterthan = 0;
} else if ($lesson->gradebetterthan > 100) {
$lesson->gradebetterthan = 100;
}
if (empty($lesson->width)) {
$lesson->width = 640;
}
if (empty($lesson->height)) {
$lesson->height = 480;
}
if (empty($lesson->bgcolor)) {
$lesson->bgcolor = '#FFFFFF';
}
// Conditions for dependency
$conditions = new stdClass;
$conditions->timespent = $lesson->timespent;
$conditions->completed = $lesson->completed;
$conditions->gradebetterthan = $lesson->gradebetterthan;
$lesson->conditions = serialize($conditions);
unset($lesson->timespent);
unset($lesson->completed);
unset($lesson->gradebetterthan);
if (empty($lesson->password)) {
unset($lesson->password);
}
}
/**
* Runs any processes that must be run
* after a lesson insert/update
*
* @global object
* @param object $lesson Lesson form data
* @return void
**/
function lesson_process_post_save(&$lesson) {
// Update the events relating to this lesson.
lesson_update_events($lesson);
$completionexpected = (!empty($lesson->completionexpected)) ? $lesson->completionexpected : null;
\core_completion\api::update_completion_date_event($lesson->coursemodule, 'lesson', $lesson, $completionexpected);
}
/**
* Implementation of the function for printing the form elements that control
* whether the course reset functionality affects the lesson.
*
* @param MoodleQuickForm $mform form passed by reference
*/
function lesson_reset_course_form_definition(&$mform) {
$mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson'));
$mform->addElement('static', 'lessondelete', get_string('delete'));
$mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts', 'lesson'));
$mform->addElement('advcheckbox', 'reset_lesson_user_overrides',
get_string('removealluseroverrides', 'lesson'));
$mform->addElement('advcheckbox', 'reset_lesson_group_overrides',
get_string('removeallgroupoverrides', 'lesson'));
}
/**
* Course reset form defaults.
* @param object $course
* @return array
*/
function lesson_reset_course_form_defaults($course) {
return array('reset_lesson' => 1,
'reset_lesson_group_overrides' => 1,
'reset_lesson_user_overrides' => 1);
}
/**
* Removes all grades from gradebook
*
* @global stdClass
* @global object
* @param int $courseid
* @param string optional type
*/
function lesson_reset_gradebook($courseid, $type='') {
global $CFG, $DB;
$sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
FROM {lesson} l, {course_modules} cm, {modules} m
WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course";
$params = array ("course" => $courseid);
if ($lessons = $DB->get_records_sql($sql,$params)) {
foreach ($lessons as $lesson) {
lesson_grade_item_update($lesson, 'reset');
}
}
}
/**
* Actual implementation of the reset course functionality, delete all the
* lesson attempts for course $data->courseid.
*
* @global stdClass
* @global object
* @param object $data the data submitted from the reset course.
* @return array status array
*/
function lesson_reset_userdata($data) {
global $CFG, $DB;
$componentstr = get_string('modulenameplural', 'lesson');
$status = [];
if (!empty($data->reset_lesson)) {
$lessonssql = "SELECT l.id
FROM {lesson} l
WHERE l.course=:course";
$params = ["course" => $data->courseid];
$lessons = $DB->get_records_sql($lessonssql, $params);
// Get rid of attempts files.
$fs = get_file_storage();
if ($lessons) {
foreach ($lessons as $lessonid => $unused) {
if (!$cm = get_coursemodule_from_instance('lesson', $lessonid)) {
continue;
}
$context = context_module::instance($cm->id);
$fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses');
$fs->delete_area_files($context->id, 'mod_lesson', 'essay_answers');
}
}
$DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params);
$DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params);
$DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params);
$DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params);
// Remove all grades from gradebook.
if (empty($data->reset_gradebook_grades)) {
lesson_reset_gradebook($data->courseid);
}
$status[] = [
'component' => $componentstr,
'item' => get_string('deleteallattempts', 'lesson'),
'error' => false,
];
}
$purgeoverrides = false;
// Remove user overrides.
if (!empty($data->reset_lesson_user_overrides)) {
$DB->delete_records_select('lesson_overrides',
'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND userid IS NOT NULL', [$data->courseid]);
$status[] = [
'component' => $componentstr,
'item' => get_string('useroverrides', 'lesson'),
'error' => false,
];
$purgeoverrides = true;
}
// Remove group overrides.
if (!empty($data->reset_lesson_group_overrides)) {
$DB->delete_records_select('lesson_overrides',
'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND groupid IS NOT NULL', [$data->courseid]);
$status[] = [
'component' => $componentstr,
'item' => get_string('groupoverrides', 'lesson'),
'error' => false,
];
$purgeoverrides = true;
}
// Updating dates - shift may be negative too.
if ($data->timeshift) {
$DB->execute("UPDATE {lesson_overrides}
SET available = available + ?
WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
AND available <> 0", [$data->timeshift, $data->courseid]);
$DB->execute("UPDATE {lesson_overrides}
SET deadline = deadline + ?
WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
AND deadline <> 0", [$data->timeshift, $data->courseid]);
$purgeoverrides = true;
// Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
// See MDL-9367.
shift_course_mod_dates('lesson', ['available', 'deadline'], $data->timeshift, $data->courseid);
$status[] = [
'component' => $componentstr,
'item' => get_string('date'),
'error' => false,
];
}
if ($purgeoverrides) {
cache::make('mod_lesson', 'overrides')->purge();
}
return $status;
}
/**
* @uses FEATURE_GROUPS
* @uses FEATURE_GROUPINGS
* @uses FEATURE_MOD_INTRO
* @uses FEATURE_COMPLETION_TRACKS_VIEWS
* @uses FEATURE_GRADE_HAS_GRADE
* @uses FEATURE_GRADE_OUTCOMES
* @param string $feature FEATURE_xx constant for requested feature
* @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
*/
function lesson_supports($feature) {
switch($feature) {
case FEATURE_GROUPS:
return true;