mirrored from git://git.moodle.org/moodle.git
/
locallib.php
2834 lines (2574 loc) · 104 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
* @subpackage 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");
//////////////////////////////////////////////////////////////////////////////////////
/// 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;
}
$params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $retakes);
if (!$seenbranches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid AND retry = :retry", $params,
"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;
}
// 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';
$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->timed || has_capability('mod/lesson:manage', $context)) {
return null;
}
$content = '<div class="jshidewhenenabled">';
$content .= $lesson->time_remaining($timer->starttime);
$content .= '</div>';
$clocksettings = array('starttime'=>$timer->starttime, 'servertime'=>time(),'testlength'=>($lesson->maxtime * 60));
$page->requires->data_for_js('clocksettings', $clocksettings);
$page->requires->js('/mod/lesson/timer.js');
$page->requires->js_function_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="skip">'.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));
$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));
$mediarenderer = $PAGE->get_renderer('core', 'media');
$embedoptions = array(
core_media::OPTION_TRUSTED => true,
core_media::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 ($mediarenderer->can_embed_url($url, $embedoptions)) {
// Media (audio/video) file.
$code = $mediarenderer->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;
}
/**
* Abstract class that page type's MUST inherit from.
*
* This is the abstract class that ALL add page type forms must extend.
* You will notice that all but two of the methods this class contains are final.
* Essentially the only thing that extending classes can do is extend custom_definition.
* OR if it has a special requirement on creation it can extend construction_override
*
* @abstract
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class lesson_add_page_form_base extends moodleform {
/**
* This is the classic define that is used to identify this pagetype.
* Will be one of LESSON_*
* @var int
*/
public $qtype;
/**
* The simple string that describes the page type e.g. truefalse, multichoice
* @var string
*/
public $qtypestring;
/**
* An array of options used in the htmleditor
* @var array
*/
protected $editoroptions = array();
/**
* True if this is a standard page of false if it does something special.
* Questions are standard pages, branch tables are not
* @var bool
*/
protected $standard = true;
/**
* Each page type can and should override this to add any custom elements to
* the basic form that they want
*/
public function custom_definition() {}
/**
* Used to determine if this is a standard page or a special page
* @return bool
*/
public final function is_standard() {
return (bool)$this->standard;
}
/**
* Add the required basic elements to the form.
*
* This method adds the basic elements to the form including title and contents
* and then calls custom_definition();
*/
public final function definition() {
$mform = $this->_form;
$editoroptions = $this->_customdata['editoroptions'];
$mform->addElement('header', 'qtypeheading', get_string('createaquestionpage', 'lesson', get_string($this->qtypestring, 'lesson')));
$mform->addElement('hidden', 'id');
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'pageid');
$mform->setType('pageid', PARAM_INT);
if ($this->standard === true) {
$mform->addElement('hidden', 'qtype');
$mform->setType('qtype', PARAM_INT);
$mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70));
$mform->setType('title', PARAM_TEXT);
$mform->addRule('title', get_string('required'), 'required', null, 'client');
$this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']);
$mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions);
$mform->setType('contents_editor', PARAM_RAW);
$mform->addRule('contents_editor', get_string('required'), 'required', null, 'client');
}
$this->custom_definition();
if ($this->_customdata['edit'] === true) {
$mform->addElement('hidden', 'edit', 1);
$mform->setType('edit', PARAM_BOOL);
$this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
} else if ($this->qtype === 'questiontype') {
$this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson'));
} else {
$this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson'));
}
}
/**
* Convenience function: Adds a jumpto select element
*
* @param string $name
* @param string|null $label
* @param int $selected The page to select by default
*/
protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) {
$title = get_string("jump", "lesson");
if ($label === null) {
$label = $title;
}
if (is_int($name)) {
$name = "jumpto[$name]";
}
$this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']);
$this->_form->setDefault($name, $selected);
$this->_form->addHelpButton($name, 'jumps', 'lesson');
}
/**
* Convenience function: Adds a score input element
*
* @param string $name
* @param string|null $label
* @param mixed $value The default value
*/
protected final function add_score($name, $label=null, $value=null) {
if ($label === null) {
$label = get_string("score", "lesson");
}
if (is_int($name)) {
$name = "score[$name]";
}
$this->_form->addElement('text', $name, $label, array('size'=>5));
$this->_form->setType($name, PARAM_INT);
if ($value !== null) {
$this->_form->setDefault($name, $value);
}
}
/**
* Convenience function: Adds an answer editor
*
* @param int $count The count of the element to add
* @param string $label, null means default
* @param bool $required
* @return void
*/
protected final function add_answer($count, $label = null, $required = false) {
if ($label === null) {
$label = get_string('answer', 'lesson');
}
$this->_form->addElement('editor', 'answer_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
$this->_form->setDefault('answer_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE));
if ($required) {
$this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client');
}
}
/**
* Convenience function: Adds an response editor
*
* @param int $count The count of the element to add
* @param string $label, null means default
* @param bool $required
* @return void
*/
protected final function add_response($count, $label = null, $required = false) {
if ($label === null) {
$label = get_string('response', 'lesson');
}
$this->_form->addElement('editor', 'response_editor['.$count.']', $label, array('rows'=>'4', 'columns'=>'80'), array('noclean'=>true));
$this->_form->setDefault('response_editor['.$count.']', array('text'=>'', 'format'=>FORMAT_MOODLE));
if ($required) {
$this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client');
}
}
/**
* A function that gets called upon init of this object by the calling script.
*
* This can be used to process an immediate action if required. Currently it
* is only used in special cases by non-standard page types.
*
* @return bool
*/
public function construction_override($pageid, lesson $lesson) {
return true;
}
}
/**
* Class representation of a lesson
*
* This class is used the interact with, and manage a lesson once instantiated.
* If you need to fetch a lesson object you can do so by calling
*
* <code>
* lesson::load($lessonid);
* // or
* $lessonrecord = $DB->get_record('lesson', $lessonid);
* $lesson = new lesson($lessonrecord);
* </code>
*
* The class itself extends lesson_base as all classes within the lesson module should
*
* These properties are from the database
* @property int $id The id of this lesson
* @property int $course The ID of the course this lesson belongs to
* @property string $name The name of this lesson
* @property int $practice Flag to toggle this as a practice lesson
* @property int $modattempts Toggle to allow the user to go back and review answers
* @property int $usepassword Toggle the use of a password for entry
* @property string $password The password to require users to enter
* @property int $dependency ID of another lesson this lesson is dependent on
* @property string $conditions Conditions of the lesson dependency
* @property int $grade The maximum grade a user can achieve (%)
* @property int $custom Toggle custom scoring on or off
* @property int $ongoing Toggle display of an ongoing score
* @property int $usemaxgrade How retakes are handled (max=1, mean=0)
* @property int $maxanswers The max number of answers or branches
* @property int $maxattempts The maximum number of attempts a user can record
* @property int $review Toggle use or wrong answer review button
* @property int $nextpagedefault Override the default next page
* @property int $feedback Toggles display of default feedback
* @property int $minquestions Sets a minimum value of pages seen when calculating grades
* @property int $maxpages Maximum number of pages this lesson can contain
* @property int $retake Flag to allow users to retake a lesson
* @property int $activitylink Relate this lesson to another lesson
* @property string $mediafile File to pop up to or webpage to display
* @property int $mediaheight Sets the height of the media file popup
* @property int $mediawidth Sets the width of the media file popup
* @property int $mediaclose Toggle display of a media close button
* @property int $slideshow Flag for whether branch pages should be shown as slideshows
* @property int $width Width of slideshow
* @property int $height Height of slideshow
* @property string $bgcolor Background colour of slideshow
* @property int $displayleft Display a left menu
* @property int $displayleftif Sets the condition on which the left menu is displayed
* @property int $progressbar Flag to toggle display of a lesson progress bar
* @property int $highscores Flag to toggle collection of high scores
* @property int $maxhighscores Number of high scores to limit to
* @property int $available Timestamp of when this lesson becomes available
* @property int $deadline Timestamp of when this lesson is no longer available
* @property int $timemodified Timestamp when lesson was last modified
*
* These properties are calculated
* @property int $firstpageid Id of the first page of this lesson (prevpageid=0)
* @property int $lastpageid Id of the last page of this lesson (nextpageid=0)
*
* @copyright 2009 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class lesson extends lesson_base {
/**
* The id of the first page (where prevpageid = 0) gets set and retrieved by
* {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code>
* @var int
*/
protected $firstpageid = null;
/**
* The id of the last page (where nextpageid = 0) gets set and retrieved by
* {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code>
* @var int
*/
protected $lastpageid = null;
/**
* An array used to cache the pages associated with this lesson after the first
* time they have been loaded.
* A note to developers: If you are going to be working with MORE than one or
* two pages from a lesson you should probably call {@see $lesson->load_all_pages()}
* in order to save excess database queries.
* @var array An array of lesson_page objects
*/
protected $pages = array();
/**
* Flag that gets set to true once all of the pages associated with the lesson
* have been loaded.
* @var bool
*/
protected $loadedallpages = false;
/**
* Simply generates a lesson object given an array/object of properties
* Overrides {@see lesson_base->create()}
* @static
* @param object|array $properties
* @return lesson
*/
public static function create($properties) {
return new lesson($properties);
}
/**
* Generates a lesson object from the database given its id
* @static
* @param int $lessonid
* @return lesson
*/
public static function load($lessonid) {
global $DB;
if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
print_error('invalidcoursemodule');
}
return new lesson($lesson);
}
/**
* Deletes this lesson from the database
*/
public function delete() {
global $CFG, $DB;
require_once($CFG->libdir.'/gradelib.php');
require_once($CFG->dirroot.'/calendar/lib.php');
$cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
$context = context_module::instance($cm->id);
$DB->delete_records("lesson", array("id"=>$this->properties->id));
$DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
$DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
$DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
$DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
$DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
$DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
$DB->delete_records("lesson_high_scores", array("lessonid"=>$this->properties->id));
if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
foreach($events as $event) {
$event = calendar_event::load($event);
$event->delete();
}
}
// Delete files associated with this module.
$fs = get_file_storage();
$fs->delete_area_files($context->id);
grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));
return true;
}
/**
* Fetches messages from the session that may have been set in previous page
* actions.
*
* <code>
* // Do not call this method directly instead use
* $lesson->messages;
* </code>
*
* @return array
*/
protected function get_messages() {
global $SESSION;
$messages = array();
if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) {
$messages = $SESSION->lesson_messages[$this->properties->id];
unset($SESSION->lesson_messages[$this->properties->id]);
}
return $messages;