forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locallib.php
5345 lines (4820 loc) · 207 KB
/
locallib.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/>.
/**
* Local library file for Lesson. These are non-standard functions that are used
* only by 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 late
**/
/** Make sure this isn't being directly accessed */
defined('MOODLE_INTERNAL') || die();
/** Include the files that are required by this module */
require_once($CFG->dirroot.'/course/moodleform_mod.php');
require_once($CFG->dirroot . '/mod/lesson/lib.php');
require_once($CFG->libdir . '/filelib.php');
/** This page */
define('LESSON_THISPAGE', 0);
/** Next page -> any page not seen before */
define("LESSON_UNSEENPAGE", 1);
/** Next page -> any page not answered correctly */
define("LESSON_UNANSWEREDPAGE", 2);
/** Jump to Next Page */
define("LESSON_NEXTPAGE", -1);
/** End of Lesson */
define("LESSON_EOL", -9);
/** Jump to an unseen page within a branch and end of branch or end of lesson */
define("LESSON_UNSEENBRANCHPAGE", -50);
/** Jump to Previous Page */
define("LESSON_PREVIOUSPAGE", -40);
/** Jump to a random page within a branch and end of branch or end of lesson */
define("LESSON_RANDOMPAGE", -60);
/** Jump to a random Branch */
define("LESSON_RANDOMBRANCH", -70);
/** Cluster Jump */
define("LESSON_CLUSTERJUMP", -80);
/** Undefined */
define("LESSON_UNDEFINED", -99);
/** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
define("LESSON_MAX_EVENT_LENGTH", "432000");
/** Answer format is HTML */
define("LESSON_ANSWER_HTML", "HTML");
/** Placeholder answer for all other answers. */
define("LESSON_OTHER_ANSWERS", "@#wronganswer#@");
//////////////////////////////////////////////////////////////////////////////////////
/// Any other lesson functions go here. Each of them must have a name that
/// starts with lesson_
/**
* Checks to see if a LESSON_CLUSTERJUMP or
* a LESSON_UNSEENBRANCHPAGE is used in a lesson.
*
* This function is only executed when a teacher is
* checking the navigation for a lesson.
*
* @param stdClass $lesson Id of the lesson that is to be checked.
* @return boolean True or false.
**/
function lesson_display_teacher_warning($lesson) {
global $DB;
// get all of the lesson answers
$params = array ("lessonid" => $lesson->id);
if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
// no answers, then not using cluster or unseen
return false;
}
// just check for the first one that fulfills the requirements
foreach ($lessonanswers as $lessonanswer) {
if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
return true;
}
}
// if no answers use either of the two jumps
return false;
}
/**
* Interprets the LESSON_UNSEENBRANCHPAGE jump.
*
* will return the pageid of a random unseen page that is within a branch
*
* @param lesson $lesson
* @param int $userid Id of the user.
* @param int $pageid Id of the page from which we are jumping.
* @return int Id of the next page.
**/
function lesson_unseen_question_jump($lesson, $user, $pageid) {
global $DB;
// get the number of retakes
if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
$retakes = 0;
}
// get all the lesson_attempts aka what the user has seen
if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
foreach($viewedpages as $viewed) {
$seenpages[] = $viewed->pageid;
}
} else {
$seenpages = array();
}
// get the lesson pages
$lessonpages = $lesson->load_all_pages();
if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series
$pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
}
// go up the pages till branch table
while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
break;
}
$pageid = $lessonpages[$pageid]->prevpageid;
}
$pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
// this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
$unseen = array();
foreach($pagesinbranch as $page) {
if (!in_array($page->id, $seenpages)) {
$unseen[] = $page->id;
}
}
if(count($unseen) == 0) {
if(isset($pagesinbranch)) {
$temp = end($pagesinbranch);
$nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
} else {
// there are no pages inside the branch, so return the next page
$nextpage = $lessonpages[$pageid]->nextpageid;
}
if ($nextpage == 0) {
return LESSON_EOL;
} else {
return $nextpage;
}
} else {
return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
}
}
/**
* Handles the unseen branch table jump.
*
* @param lesson $lesson
* @param int $userid User id.
* @return int Will return the page id of a branch table or end of lesson
**/
function lesson_unseen_branch_jump($lesson, $userid) {
global $DB;
if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
$retakes = 0;
}
if (!$seenbranches = $lesson->get_content_pages_viewed($retakes, $userid, 'timeseen DESC')) {
print_error('cannotfindrecords', 'lesson');
}
// get the lesson pages
$lessonpages = $lesson->load_all_pages();
// this loads all the viewed branch tables into $seen until it finds the branch table with the flag
// which is the branch table that starts the unseenbranch function
$seen = array();
foreach ($seenbranches as $seenbranch) {
if (!$seenbranch->flag) {
$seen[$seenbranch->pageid] = $seenbranch->pageid;
} else {
$start = $seenbranch->pageid;
break;
}
}
// this function searches through the lesson pages to find all the branch tables
// that follow the flagged branch table
$pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
$branchtables = array();
while ($pageid != 0) { // grab all of the branch table till eol
if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
$branchtables[] = $lessonpages[$pageid]->id;
}
$pageid = $lessonpages[$pageid]->nextpageid;
}
$unseen = array();
foreach ($branchtables as $branchtable) {
// load all of the unseen branch tables into unseen
if (!array_key_exists($branchtable, $seen)) {
$unseen[] = $branchtable;
}
}
if (count($unseen) > 0) {
return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
} else {
return LESSON_EOL; // has viewed all of the branch tables
}
}
/**
* Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
*
* @param lesson $lesson
* @param int $pageid The id of the page that we are jumping from (?)
* @return int The pageid of a random page that is within a branch table
**/
function lesson_random_question_jump($lesson, $pageid) {
global $DB;
// get the lesson pages
$params = array ("lessonid" => $lesson->id);
if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
print_error('cannotfindpages', 'lesson');
}
// go up the pages till branch table
while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
break;
}
$pageid = $lessonpages[$pageid]->prevpageid;
}
// get the pages within the branch
$pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
if(count($pagesinbranch) == 0) {
// there are no pages inside the branch, so return the next page
return $lessonpages[$pageid]->nextpageid;
} else {
return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
}
}
/**
* Calculates a user's grade for a lesson.
*
* @param object $lesson The lesson that the user is taking.
* @param int $retries The attempt number.
* @param int $userid Id of the user (optional, default current user).
* @return object { nquestions => number of questions answered
attempts => number of question attempts
total => max points possible
earned => points earned by student
grade => calculated percentage grade
nmanual => number of manually graded questions
manualpoints => point value for manually graded questions }
*/
function lesson_grade($lesson, $ntries, $userid = 0) {
global $USER, $DB;
if (empty($userid)) {
$userid = $USER->id;
}
// Zero out everything
$ncorrect = 0;
$nviewed = 0;
$score = 0;
$nmanual = 0;
$manualpoints = 0;
$thegrade = 0;
$nquestions = 0;
$total = 0;
$earned = 0;
$params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
userid = :userid AND retry = :retry", $params, "timeseen")) {
// group each try with its page
$attemptset = array();
foreach ($useranswers as $useranswer) {
$attemptset[$useranswer->pageid][] = $useranswer;
}
if (!empty($lesson->maxattempts)) {
// Drop all attempts that go beyond max attempts for the lesson.
foreach ($attemptset as $key => $set) {
$attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
}
}
// get only the pages and their answers that the user answered
list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
array_unshift($parameters, $lesson->id);
$pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
$answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
// Number of pages answered
$nquestions = count($pages);
foreach ($attemptset as $attempts) {
$page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
if ($lesson->custom) {
$attempt = end($attempts);
// If essay question, handle it, otherwise add to score
if ($page->requires_manual_grading()) {
$useranswerobj = unserialize($attempt->useranswer);
if (isset($useranswerobj->score)) {
$earned += $useranswerobj->score;
}
$nmanual++;
$manualpoints += $answers[$attempt->answerid]->score;
} else if (!empty($attempt->answerid)) {
$earned += $page->earned_score($answers, $attempt);
}
} else {
foreach ($attempts as $attempt) {
$earned += $attempt->correct;
}
$attempt = end($attempts); // doesn't matter which one
// If essay question, increase numbers
if ($page->requires_manual_grading()) {
$nmanual++;
$manualpoints++;
}
}
// Number of times answered
$nviewed += count($attempts);
}
if ($lesson->custom) {
$bestscores = array();
// Find the highest possible score per page to get our total
foreach ($answers as $answer) {
if(!isset($bestscores[$answer->pageid])) {
$bestscores[$answer->pageid] = $answer->score;
} else if ($bestscores[$answer->pageid] < $answer->score) {
$bestscores[$answer->pageid] = $answer->score;
}
}
$total = array_sum($bestscores);
} else {
// Check to make sure the student has answered the minimum questions
if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
// Nope, increase number viewed by the amount of unanswered questions
$total = $nviewed + ($lesson->minquestions - $nquestions);
} else {
$total = $nviewed;
}
}
}
if ($total) { // not zero
$thegrade = round(100 * $earned / $total, 5);
}
// Build the grade information object
$gradeinfo = new stdClass;
$gradeinfo->nquestions = $nquestions;
$gradeinfo->attempts = $nviewed;
$gradeinfo->total = $total;
$gradeinfo->earned = $earned;
$gradeinfo->grade = $thegrade;
$gradeinfo->nmanual = $nmanual;
$gradeinfo->manualpoints = $manualpoints;
return $gradeinfo;
}
/**
* Determines if a user can view the left menu. The determining factor
* is whether a user has a grade greater than or equal to the lesson setting
* of displayleftif
*
* @param object $lesson Lesson object of the current lesson
* @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
**/
function lesson_displayleftif($lesson) {
global $CFG, $USER, $DB;
if (!empty($lesson->displayleftif)) {
// get the current user's max grade for this lesson
$params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
if ($maxgrade = $DB->get_record_sql('SELECT userid, MAX(grade) AS maxgrade FROM {lesson_grades} WHERE userid = :userid AND lessonid = :lessonid GROUP BY userid', $params)) {
if ($maxgrade->maxgrade < $lesson->displayleftif) {
return 0; // turn off the displayleft
}
} else {
return 0; // no grades
}
}
// if we get to here, keep the original state of displayleft lesson setting
return $lesson->displayleft;
}
/**
*
* @param $cm
* @param $lesson
* @param $page
* @return unknown_type
*/
function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
$bc = lesson_menu_block_contents($cm->id, $lesson);
if (!empty($bc)) {
$regions = $page->blocks->get_regions();
$firstregion = reset($regions);
$page->blocks->add_fake_block($bc, $firstregion);
}
$bc = lesson_mediafile_block_contents($cm->id, $lesson);
if (!empty($bc)) {
$page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
}
if (!empty($timer)) {
$bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
if (!empty($bc)) {
$page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
}
}
}
/**
* If there is a media file associated with this
* lesson, return a block_contents that displays it.
*
* @param int $cmid Course Module ID for this lesson
* @param object $lesson Full lesson record object
* @return block_contents
**/
function lesson_mediafile_block_contents($cmid, $lesson) {
global $OUTPUT;
if (empty($lesson->mediafile)) {
return null;
}
$options = array();
$options['menubar'] = 0;
$options['location'] = 0;
$options['left'] = 5;
$options['top'] = 5;
$options['scrollbars'] = 1;
$options['resizable'] = 1;
$options['width'] = $lesson->mediawidth;
$options['height'] = $lesson->mediaheight;
$link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
$action = new popup_action('click', $link, 'lessonmediafile', $options);
$content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
$bc = new block_contents();
$bc->title = get_string('linkedmedia', 'lesson');
$bc->attributes['class'] = 'mediafile block';
$bc->content = $content;
return $bc;
}
/**
* If a timed lesson and not a teacher, then
* return a block_contents containing the clock.
*
* @param int $cmid Course Module ID for this lesson
* @param object $lesson Full lesson record object
* @param object $timer Full timer record object
* @return block_contents
**/
function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
// Display for timed lessons and for students only
$context = context_module::instance($cmid);
if ($lesson->timelimit == 0 || has_capability('mod/lesson:manage', $context)) {
return null;
}
$content = '<div id="lesson-timer">';
$content .= $lesson->time_remaining($timer->starttime);
$content .= '</div>';
$clocksettings = array('starttime' => $timer->starttime, 'servertime' => time(), 'testlength' => $lesson->timelimit);
$page->requires->data_for_js('clocksettings', $clocksettings, true);
$page->requires->strings_for_js(array('timeisup'), 'lesson');
$page->requires->js('/mod/lesson/timer.js');
$page->requires->js_init_call('show_clock');
$bc = new block_contents();
$bc->title = get_string('timeremaining', 'lesson');
$bc->attributes['class'] = 'clock block';
$bc->content = $content;
return $bc;
}
/**
* If left menu is turned on, then this will
* print the menu in a block
*
* @param int $cmid Course Module ID for this lesson
* @param lesson $lesson Full lesson record object
* @return void
**/
function lesson_menu_block_contents($cmid, $lesson) {
global $CFG, $DB;
if (!$lesson->displayleft) {
return null;
}
$pages = $lesson->load_all_pages();
foreach ($pages as $page) {
if ((int)$page->prevpageid === 0) {
$pageid = $page->id;
break;
}
}
$currentpageid = optional_param('pageid', $pageid, PARAM_INT);
if (!$pageid || !$pages) {
return null;
}
$content = '<a href="#maincontent" class="accesshide">' .
get_string('skip', 'lesson') .
"</a>\n<div class=\"menuwrapper\">\n<ul>\n";
while ($pageid != 0) {
$page = $pages[$pageid];
// Only process branch tables with display turned on
if ($page->displayinmenublock && $page->display) {
if ($page->id == $currentpageid) {
$content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
} else {
$content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&pageid=$page->id\">".format_string($page->title,true)."</a></li>\n";
}
}
$pageid = $page->nextpageid;
}
$content .= "</ul>\n</div>\n";
$bc = new block_contents();
$bc->title = get_string('lessonmenu', 'lesson');
$bc->attributes['class'] = 'menu block';
$bc->content = $content;
return $bc;
}
/**
* Adds header buttons to the page for the lesson
*
* @param object $cm
* @param object $context
* @param bool $extraeditbuttons
* @param int $lessonpageid
*/
function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
global $CFG, $PAGE, $OUTPUT;
if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
if ($lessonpageid === null) {
print_error('invalidpageid', 'lesson');
}
if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
$url = new moodle_url('/mod/lesson/editpage.php', array(
'id' => $cm->id,
'pageid' => $lessonpageid,
'edit' => 1,
'returnto' => $PAGE->url->out_as_local_url(false)
));
$PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
}
}
}
/**
* This is a function used to detect media types and generate html code.
*
* @global object $CFG
* @global object $PAGE
* @param object $lesson
* @param object $context
* @return string $code the html code of media
*/
function lesson_get_media_html($lesson, $context) {
global $CFG, $PAGE, $OUTPUT;
require_once("$CFG->libdir/resourcelib.php");
// get the media file link
if (strpos($lesson->mediafile, '://') !== false) {
$url = new moodle_url($lesson->mediafile);
} else {
// the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
$url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
}
$title = $lesson->mediafile;
$clicktoopen = html_writer::link($url, get_string('download'));
$mimetype = resourcelib_guess_url_mimetype($url);
$extension = resourcelib_get_extension($url->out(false));
$mediamanager = core_media_manager::instance($PAGE);
$embedoptions = array(
core_media_manager::OPTION_TRUSTED => true,
core_media_manager::OPTION_BLOCK => true
);
// find the correct type and print it out
if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
$code = resourcelib_embed_image($url, $title);
} else if ($mediamanager->can_embed_url($url, $embedoptions)) {
// Media (audio/video) file.
$code = $mediamanager->embed_url($url, $title, 0, 0, $embedoptions);
} else {
// anything else - just try object tag enlarged as much as possible
$code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
}
return $code;
}
/**
* Logic to happen when a/some group(s) has/have been deleted in a course.
*
* @param int $courseid The course ID.
* @param int $groupid The group id if it is known
* @return void
*/
function lesson_process_group_deleted_in_course($courseid, $groupid = null) {
global $DB;
$params = array('courseid' => $courseid);
if ($groupid) {
$params['groupid'] = $groupid;
// We just update the group that was deleted.
$sql = "SELECT o.id, o.lessonid
FROM {lesson_overrides} o
JOIN {lesson} lesson ON lesson.id = o.lessonid
WHERE lesson.course = :courseid
AND o.groupid = :groupid";
} else {
// No groupid, we update all orphaned group overrides for all lessons in course.
$sql = "SELECT o.id, o.lessonid
FROM {lesson_overrides} o
JOIN {lesson} lesson ON lesson.id = o.lessonid
LEFT JOIN {groups} grp ON grp.id = o.groupid
WHERE lesson.course = :courseid
AND o.groupid IS NOT NULL
AND grp.id IS NULL";
}
$records = $DB->get_records_sql_menu($sql, $params);
if (!$records) {
return; // Nothing to do.
}
$DB->delete_records_list('lesson_overrides', 'id', array_keys($records));
}
/**
* Return the overview report table and data.
*
* @param lesson $lesson lesson instance
* @param mixed $currentgroup false if not group used, 0 for all groups, group id (int) to filter by that groups
* @return mixed false if there is no information otherwise html_table and stdClass with the table and data
* @since Moodle 3.3
*/
function lesson_get_overview_report_table_and_data(lesson $lesson, $currentgroup) {
global $DB, $CFG, $OUTPUT;
require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php');
$context = $lesson->context;
$cm = $lesson->cm;
// Count the number of branch and question pages in this lesson.
$branchcount = $DB->count_records('lesson_pages', array('lessonid' => $lesson->id, 'qtype' => LESSON_PAGE_BRANCHTABLE));
$questioncount = ($DB->count_records('lesson_pages', array('lessonid' => $lesson->id)) - $branchcount);
// Only load students if there attempts for this lesson.
$attempts = $DB->record_exists('lesson_attempts', array('lessonid' => $lesson->id));
$branches = $DB->record_exists('lesson_branch', array('lessonid' => $lesson->id));
$timer = $DB->record_exists('lesson_timer', array('lessonid' => $lesson->id));
if ($attempts or $branches or $timer) {
list($esql, $params) = get_enrolled_sql($context, '', $currentgroup, true);
list($sort, $sortparams) = users_order_by_sql('u');
$extrafields = get_extra_user_fields($context);
$params['a1lessonid'] = $lesson->id;
$params['b1lessonid'] = $lesson->id;
$params['c1lessonid'] = $lesson->id;
$ufields = user_picture::fields('u', $extrafields);
$sql = "SELECT DISTINCT $ufields
FROM {user} u
JOIN (
SELECT userid, lessonid FROM {lesson_attempts} a1
WHERE a1.lessonid = :a1lessonid
UNION
SELECT userid, lessonid FROM {lesson_branch} b1
WHERE b1.lessonid = :b1lessonid
UNION
SELECT userid, lessonid FROM {lesson_timer} c1
WHERE c1.lessonid = :c1lessonid
) a ON u.id = a.userid
JOIN ($esql) ue ON ue.id = a.userid
ORDER BY $sort";
$students = $DB->get_recordset_sql($sql, $params);
if (!$students->valid()) {
$students->close();
return array(false, false);
}
} else {
return array(false, false);
}
if (! $grades = $DB->get_records('lesson_grades', array('lessonid' => $lesson->id), 'completed')) {
$grades = array();
}
if (! $times = $DB->get_records('lesson_timer', array('lessonid' => $lesson->id), 'starttime')) {
$times = array();
}
// Build an array for output.
$studentdata = array();
$attempts = $DB->get_recordset('lesson_attempts', array('lessonid' => $lesson->id), 'timeseen');
foreach ($attempts as $attempt) {
// if the user is not in the array or if the retry number is not in the sub array, add the data for that try.
if (empty($studentdata[$attempt->userid]) || empty($studentdata[$attempt->userid][$attempt->retry])) {
// restore/setup defaults
$n = 0;
$timestart = 0;
$timeend = 0;
$usergrade = null;
$eol = 0;
// search for the grade record for this try. if not there, the nulls defined above will be used.
foreach($grades as $grade) {
// check to see if the grade matches the correct user
if ($grade->userid == $attempt->userid) {
// see if n is = to the retry
if ($n == $attempt->retry) {
// get grade info
$usergrade = round($grade->grade, 2); // round it here so we only have to do it once
break;
}
$n++; // if not equal, then increment n
}
}
$n = 0;
// search for the time record for this try. if not there, the nulls defined above will be used.
foreach($times as $time) {
// check to see if the grade matches the correct user
if ($time->userid == $attempt->userid) {
// see if n is = to the retry
if ($n == $attempt->retry) {
// get grade info
$timeend = $time->lessontime;
$timestart = $time->starttime;
$eol = $time->completed;
break;
}
$n++; // if not equal, then increment n
}
}
// build up the array.
// this array represents each student and all of their tries at the lesson
$studentdata[$attempt->userid][$attempt->retry] = array( "timestart" => $timestart,
"timeend" => $timeend,
"grade" => $usergrade,
"end" => $eol,
"try" => $attempt->retry,
"userid" => $attempt->userid);
}
}
$attempts->close();
$branches = $DB->get_recordset('lesson_branch', array('lessonid' => $lesson->id), 'timeseen');
foreach ($branches as $branch) {
// If the user is not in the array or if the retry number is not in the sub array, add the data for that try.
if (empty($studentdata[$branch->userid]) || empty($studentdata[$branch->userid][$branch->retry])) {
// Restore/setup defaults.
$n = 0;
$timestart = 0;
$timeend = 0;
$usergrade = null;
$eol = 0;
// Search for the time record for this try. if not there, the nulls defined above will be used.
foreach ($times as $time) {
// Check to see if the grade matches the correct user.
if ($time->userid == $branch->userid) {
// See if n is = to the retry.
if ($n == $branch->retry) {
// Get grade info.
$timeend = $time->lessontime;
$timestart = $time->starttime;
$eol = $time->completed;
break;
}
$n++; // If not equal, then increment n.
}
}
// Build up the array.
// This array represents each student and all of their tries at the lesson.
$studentdata[$branch->userid][$branch->retry] = array( "timestart" => $timestart,
"timeend" => $timeend,
"grade" => $usergrade,
"end" => $eol,
"try" => $branch->retry,
"userid" => $branch->userid);
}
}
$branches->close();
// Need the same thing for timed entries that were not completed.
foreach ($times as $time) {
$endoflesson = $time->completed;
// If the time start is the same with another record then we shouldn't be adding another item to this array.
if (isset($studentdata[$time->userid])) {
$foundmatch = false;
$n = 0;
foreach ($studentdata[$time->userid] as $key => $value) {
if ($value['timestart'] == $time->starttime) {
// Don't add this to the array.
$foundmatch = true;
break;
}
}
$n = count($studentdata[$time->userid]) + 1;
if (!$foundmatch) {
// Add a record.
$studentdata[$time->userid][] = array(
"timestart" => $time->starttime,
"timeend" => $time->lessontime,
"grade" => null,
"end" => $endoflesson,
"try" => $n,
"userid" => $time->userid
);
}
} else {
$studentdata[$time->userid][] = array(
"timestart" => $time->starttime,
"timeend" => $time->lessontime,
"grade" => null,
"end" => $endoflesson,
"try" => 0,
"userid" => $time->userid
);
}
}
// To store all the data to be returned by the function.
$data = new stdClass();
// Determine if lesson should have a score.
if ($branchcount > 0 AND $questioncount == 0) {
// This lesson only contains content pages and is not graded.
$data->lessonscored = false;
} else {
// This lesson is graded.
$data->lessonscored = true;
}
// set all the stats variables
$data->numofattempts = 0;
$data->avescore = 0;
$data->avetime = 0;
$data->highscore = null;
$data->lowscore = null;
$data->hightime = null;
$data->lowtime = null;
$data->students = array();
$table = new html_table();
$headers = [get_string('name')];
foreach ($extrafields as $field) {
$headers[] = get_user_field_name($field);
}
$caneditlesson = has_capability('mod/lesson:edit', $context);
$attemptsheader = get_string('attempts', 'lesson');
if ($caneditlesson) {
$selectall = get_string('selectallattempts', 'lesson');
$deselectall = get_string('deselectallattempts', 'lesson');
// Build the select/deselect all control.
$selectallid = 'selectall-attempts';
$mastercheckbox = new \core\output\checkbox_toggleall('lesson-attempts', true, [
'id' => $selectallid,
'name' => $selectallid,
'value' => 1,
'label' => $selectall,
'selectall' => $selectall,
'deselectall' => $deselectall,
'labelclasses' => 'form-check-label'
]);
$attemptsheader = $OUTPUT->render($mastercheckbox);
}
$headers [] = $attemptsheader;
// Set up the table object.
if ($data->lessonscored) {
$headers [] = get_string('highscore', 'lesson');
}
$colcount = count($headers);
$table->head = $headers;
$table->align = [];
$table->align = array_pad($table->align, $colcount, 'center');
$table->align[$colcount - 1] = 'left';
if ($data->lessonscored) {
$table->align[$colcount - 2] = 'left';
}
$table->wrap = [];
$table->wrap = array_pad($table->wrap, $colcount, 'nowrap');
$table->attributes['class'] = 'table table-striped';
// print out the $studentdata array
// going through each student that has attempted the lesson, so, each student should have something to be displayed
foreach ($students as $student) {
// check to see if the student has attempts to print out
if (array_key_exists($student->id, $studentdata)) {
// set/reset some variables
$attempts = array();
$dataforstudent = new stdClass;
$dataforstudent->attempts = array();
// gather the data for each user attempt
$bestgrade = 0;
// $tries holds all the tries/retries a student has done
$tries = $studentdata[$student->id];
$studentname = fullname($student, true);
foreach ($tries as $try) {
$dataforstudent->attempts[] = $try;
// Start to build up the checkbox and link.
$attempturlparams = [
'id' => $cm->id,
'action' => 'reportdetail',
'userid' => $try['userid'],
'try' => $try['try'],
];
if ($try["grade"] !== null) { // if null then not done yet
// this is what the link does when the user has completed the try
$timetotake = $try["timeend"] - $try["timestart"];
if ($try["grade"] > $bestgrade) {
$bestgrade = $try["grade"];
}
$attemptdata = (object)[
'grade' => $try["grade"],
'timestart' => userdate($try["timestart"]),
'duration' => format_time($timetotake),
];
$attemptlinkcontents = get_string('attemptinfowithgrade', 'lesson', $attemptdata);
} else {
if ($try["end"]) {
// User finished the lesson but has no grade. (Happens when there are only content pages).
$timetotake = $try["timeend"] - $try["timestart"];
$attemptdata = (object)[
'timestart' => userdate($try["timestart"]),
'duration' => format_time($timetotake),
];
$attemptlinkcontents = get_string('attemptinfonograde', 'lesson', $attemptdata);
} else {