Now we are using the new sql_order_by_text() function
[moodle.git] / mod / lesson / locallib.php
CommitLineData
9fcf51d9 1<?php // $Id$
62eda6ea 2/// mnielsen
5e7856af 3/// locallib.php is the new lib file for lesson module.
4/// including locallib.php is the same as including the old lib.php
4b55d2af 5
6/**
7* Next page -> any page not seen before
8*/
5e7856af 9if (!defined("LESSON_UNSEENPAGE")) {
ac8e16be 10 define("LESSON_UNSEENPAGE", 1); // Next page -> any page not seen before
4b55d2af 11}
12/**
13* Next page -> any page not answered correctly
14*/
5e7856af 15if (!defined("LESSON_UNANSWEREDPAGE")) {
ac8e16be 16 define("LESSON_UNANSWEREDPAGE", 2); // Next page -> any page not answered correctly
4b55d2af 17}
5e7856af 18
4b55d2af 19/**
20* Define different lesson flows for next page
21*/
5e7856af 22$LESSON_NEXTPAGE_ACTION = array (0 => get_string("normal", "lesson"),
23 LESSON_UNSEENPAGE => get_string("showanunseenpage", "lesson"),
24 LESSON_UNANSWEREDPAGE => get_string("showanunansweredpage", "lesson") );
25
4b55d2af 26// Lesson jump types defined
27// TODO: instead of using define statements, create an array with all the jump values
5e7856af 28
4b55d2af 29/**
30 * Jump to Next Page
31 */
5e7856af 32if (!defined("LESSON_NEXTPAGE")) {
4b55d2af 33 define("LESSON_NEXTPAGE", -1);
34}
35/**
36 * End of Lesson
37 */
5e7856af 38if (!defined("LESSON_EOL")) {
4b55d2af 39 define("LESSON_EOL", -9);
40}
41/**
42 * Jump to an unseen page within a branch and end of branch or end of lesson
43 */
5e7856af 44if (!defined("LESSON_UNSEENBRANCHPAGE")) {
4b55d2af 45 define("LESSON_UNSEENBRANCHPAGE", -50);
46}
47/**
48 * Jump to Previous Page
49 */
5e7856af 50if (!defined("LESSON_PREVIOUSPAGE")) {
4b55d2af 51 define("LESSON_PREVIOUSPAGE", -40);
52}
53/**
54 * Jump to a random page within a branch and end of branch or end of lesson
55 */
5e7856af 56if (!defined("LESSON_RANDOMPAGE")) {
4b55d2af 57 define("LESSON_RANDOMPAGE", -60);
58}
59/**
60 * Jump to a random Branch
61 */
5e7856af 62if (!defined("LESSON_RANDOMBRANCH")) {
4b55d2af 63 define("LESSON_RANDOMBRANCH", -70);
64}
65/**
66 * Cluster Jump
67 */
5e7856af 68if (!defined("LESSON_CLUSTERJUMP")) {
4b55d2af 69 define("LESSON_CLUSTERJUMP", -80);
70}
71/**
72 * Undefined
73 */
5e7856af 74if (!defined("LESSON_UNDEFINED")) {
4b55d2af 75 define("LESSON_UNDEFINED", -99);
76}
77
78// Lesson question types defined
5e7856af 79
4b55d2af 80/**
81 * Short answer question type
82 */
5e7856af 83if (!defined("LESSON_SHORTANSWER")) {
84 define("LESSON_SHORTANSWER", "1");
85}
4b55d2af 86/**
87 * True/False question type
88 */
5e7856af 89if (!defined("LESSON_TRUEFALSE")) {
90 define("LESSON_TRUEFALSE", "2");
91}
4b55d2af 92/**
93 * Multichoice question type
94 *
95 * If you change the value of this then you need
96 * to change it in restorelib.php as well.
97 */
98if (!defined("LESSON_MULTICHOICE")) {
5e7856af 99 define("LESSON_MULTICHOICE", "3");
100}
4b55d2af 101/**
102 * Random question type - not used
103 */
5e7856af 104if (!defined("LESSON_RANDOM")) {
105 define("LESSON_RANDOM", "4");
106}
4b55d2af 107/**
108 * Matching question type
109 *
110 * If you change the value of this then you need
111 * to change it in restorelib.php, in mysql.php
112 * and postgres7.php as well.
113 */
114if (!defined("LESSON_MATCHING")) {
b9869082 115 define("LESSON_MATCHING", "5");
5e7856af 116}
4b55d2af 117/**
118 * Not sure - not used
119 */
5e7856af 120if (!defined("LESSON_RANDOMSAMATCH")) {
121 define("LESSON_RANDOMSAMATCH", "6");
122}
4b55d2af 123/**
124 * Not sure - not used
125 */
5e7856af 126if (!defined("LESSON_DESCRIPTION")) {
127 define("LESSON_DESCRIPTION", "7");
128}
4b55d2af 129/**
130 * Numerical question type
131 */
5e7856af 132if (!defined("LESSON_NUMERICAL")) {
133 define("LESSON_NUMERICAL", "8");
134}
4b55d2af 135/**
136 * Multichoice with multianswer question type
137 */
5e7856af 138if (!defined("LESSON_MULTIANSWER")) {
139 define("LESSON_MULTIANSWER", "9");
140}
4b55d2af 141/**
142 * Essay question type
143 */
5e7856af 144if (!defined("LESSON_ESSAY")) {
ac8e16be 145 define("LESSON_ESSAY", "10");
5e7856af 146}
5e7856af 147
4b55d2af 148/**
149 * Lesson question type array.
150 * Contains all question types used
151 */
5e7856af 152$LESSON_QUESTION_TYPE = array ( LESSON_MULTICHOICE => get_string("multichoice", "quiz"),
153 LESSON_TRUEFALSE => get_string("truefalse", "quiz"),
154 LESSON_SHORTANSWER => get_string("shortanswer", "quiz"),
155 LESSON_NUMERICAL => get_string("numerical", "quiz"),
156 LESSON_MATCHING => get_string("match", "quiz"),
62eda6ea 157 LESSON_ESSAY => get_string("essay", "lesson")
5e7856af 158// LESSON_DESCRIPTION => get_string("description", "quiz"),
159// LESSON_RANDOM => get_string("random", "quiz"),
160// LESSON_RANDOMSAMATCH => get_string("randomsamatch", "quiz"),
161// LESSON_MULTIANSWER => get_string("multianswer", "quiz"),
162 );
163
4b55d2af 164// Non-question page types
165
166/**
167 * Branch Table page
168 */
5e7856af 169if (!defined("LESSON_BRANCHTABLE")) {
170 define("LESSON_BRANCHTABLE", "20");
171}
4b55d2af 172/**
173 * End of Branch page
174 */
5e7856af 175if (!defined("LESSON_ENDOFBRANCH")) {
176 define("LESSON_ENDOFBRANCH", "21");
177}
4b55d2af 178/**
179 * Start of Cluster page
180 */
181if (!defined("LESSON_CLUSTER")) {
182 define("LESSON_CLUSTER", "30");
183}
184/**
185 * End of Cluster page
186 */
187if (!defined("LESSON_ENDOFCLUSTER")) {
188 define("LESSON_ENDOFCLUSTER", "31");
189}
190
191// other variables...
5e7856af 192
4b55d2af 193/**
194 * Flag for the editor for the answer textarea.
195 */
5e7856af 196if (!defined("LESSON_ANSWER_EDITOR")) {
197 define("LESSON_ANSWER_EDITOR", "1");
198}
4b55d2af 199/**
200 * Flag for the editor for the response textarea.
201 */
5e7856af 202if (!defined("LESSON_RESPONSE_EDITOR")) {
203 define("LESSON_RESPONSE_EDITOR", "2");
204}
205
206//////////////////////////////////////////////////////////////////////////////////////
207/// Any other lesson functions go here. Each of them must have a name that
208/// starts with lesson_
209
9fcf51d9 210/**
211 * Print the standard header for lesson module
212 *
213 * @param object $cm Course module record object
214 * @param object $course Couse record object
215 * @param object $lesson Lesson module record object
216 * @param string $currenttab Current tab for the lesson tabs
217 * @param boolean $printheading Print the a heading with the lesson name
218 * @return void
219 **/
220function lesson_print_header($cm, $course, $lesson, $currenttab = '', $printheading = true) {
221 global $CFG, $USER;
6e1ff5c8 222 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
9fcf51d9 223
224/// Header setup
225 if ($course->category) {
226 $navigation = "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\" title=\"$course->fullname\">$course->shortname</a> ->";
227 } else {
228 $navigation = '';
229 }
230
231 $strlessons = get_string('modulenameplural', 'lesson');
232 $strlesson = get_string('modulename', 'lesson');
233 $strname = format_string($lesson->name, true);
234
235/// Print header, heading, tabs and messages
236 print_header("$course->shortname: $strname", $course->fullname,
237 "$navigation <a href=\"index.php?id=$course->id\" title=\"$strlessons\">$strlessons</a> -> $strname",
238 '', '', true, update_module_button($cm->id, $course->id, $strlesson),
239 navmenu($course, $cm));
240
241 if ($printheading) {
242 print_heading_with_help(format_string($lesson->name, true), "overview", "lesson");
243 }
244
6e1ff5c8 245 if (!empty($currenttab) and has_capability('mod/lesson:manage', $context)) {
9fcf51d9 246 include($CFG->dirroot.'/mod/lesson/tabs.php');
247 }
f15eb92c 248
249 lesson_print_messages();
9fcf51d9 250}
251
252/**
253 * Returns course module, course and module instance given
254 * either the course module ID or a lesson module ID.
255 *
256 * @param int $cmid Course Module ID
257 * @param int $lessonid Lesson module instance ID
258 * @return array array($cm, $course, $lesson)
259 **/
260function lesson_get_basics($cmid = 0, $lessonid = 0) {
261 if ($cmid) {
f15eb92c 262 if (!$cm = get_coursemodule_from_id('lesson', $cmid)) {
9fcf51d9 263 error('Course Module ID was incorrect');
264 }
265 if (!$course = get_record('course', 'id', $cm->course)) {
266 error('Course is misconfigured');
267 }
268 if (!$lesson = get_record('lesson', 'id', $cm->instance)) {
269 error('Course module is incorrect');
270 }
271 } else if ($lessonid) {
272 if (!$lesson = get_record('lesson', 'id', $lessonid)) {
273 error('Course module is incorrect');
274 }
275 if (!$course = get_record('course', 'id', $lesson->course)) {
276 error('Course is misconfigured');
277 }
278 if (!$cm = get_coursemodule_from_instance('lesson', $lesson->id, $course->id)) {
279 error('Course Module ID was incorrect');
280 }
281 } else {
282 error('No course module ID or lesson ID were passed');
283 }
284
285 return array($cm, $course, $lesson);
286}
287
6e1ff5c8 288/**
289 * Sets a message to be printed. Messages are printed
290 * by calling {@link lesson_print_messages()}.
291 *
292 * @uses $SESSION
293 * @param string $message The message to be printed
294 * @param string $class Class to be passed to {@link notify()}. Usually notifyproblem or notifysuccess.
295 * @param string $align Alignment of the message
296 * @return boolean
297 **/
298function lesson_set_message($message, $class="notifyproblem", $align='center') {
299 global $SESSION;
300
301 if (empty($SESSION->lesson_messages) or !is_array($SESSION->lesson_messages)) {
302 $SESSION->lesson_messages = array();
303 }
304
305 $SESSION->lesson_messages[] = array($message, $class, $align);
306
307 return true;
308}
309
310/**
311 * Print all set messages.
312 *
313 * See {@link lesson_set_message()} for setting messages.
314 *
315 * Uses {@link notify()} to print the messages.
316 *
317 * @uses $SESSION
318 * @return boolean
319 **/
320function lesson_print_messages() {
321 global $SESSION;
322
323 if (empty($SESSION->lesson_messages)) {
324 // No messages to print
325 return true;
326 }
327
328 foreach($SESSION->lesson_messages as $message) {
329 notify($message[0], $message[1], $message[2]);
330 }
331
332 // Reset
333 unset($SESSION->lesson_messages);
334
335 return true;
336}
337
4b55d2af 338/**
339 * Given some question info and some data about the the answers
340 * this function parses, organises and saves the question
341 *
342 * This is only used when IMPORTING questions and is only called
343 * from format.php
344 * Lifted from mod/quiz/lib.php -
345 * 1. all reference to oldanswers removed
346 * 2. all reference to quiz_multichoice table removed
347 * 3. In SHORTANSWER questions usecase is store in the qoption field
348 * 4. In NUMERIC questions store the range as two answers
349 * 5. TRUEFALSE options are ignored
350 * 6. For MULTICHOICE questions with more than one answer the qoption field is true
351 *
352 * @param opject $question Contains question data like question, type and answers.
353 * @return object Returns $result->error or $result->notice.
354 **/
5e7856af 355function lesson_save_question_options($question) {
5e7856af 356
357 $timenow = time();
358 switch ($question->qtype) {
359 case LESSON_SHORTANSWER:
360
361 $answers = array();
362 $maxfraction = -1;
363
364 // Insert all the new answers
365 foreach ($question->answer as $key => $dataanswer) {
366 if ($dataanswer != "") {
f7ffb898 367 $answer = new stdClass;
5e7856af 368 $answer->lessonid = $question->lessonid;
369 $answer->pageid = $question->id;
370 if ($question->fraction[$key] >=0.5) {
371 $answer->jumpto = LESSON_NEXTPAGE;
372 }
373 $answer->timecreated = $timenow;
374 $answer->grade = $question->fraction[$key] * 100;
375 $answer->answer = $dataanswer;
c87a341c 376 $answer->response = $question->feedback[$key];
5e7856af 377 if (!$answer->id = insert_record("lesson_answers", $answer)) {
378 $result->error = "Could not insert shortanswer quiz answer!";
379 return $result;
380 }
381 $answers[] = $answer->id;
382 if ($question->fraction[$key] > $maxfraction) {
383 $maxfraction = $question->fraction[$key];
384 }
385 }
386 }
387
388
389 /// Perform sanity checks on fractional grades
390 if ($maxfraction != 1) {
391 $maxfraction = $maxfraction * 100;
392 $result->notice = get_string("fractionsnomax", "quiz", $maxfraction);
393 return $result;
394 }
395 break;
396
397 case LESSON_NUMERICAL: // Note similarities to SHORTANSWER
398
399 $answers = array();
400 $maxfraction = -1;
401
402
403 // for each answer store the pair of min and max values even if they are the same
404 foreach ($question->answer as $key => $dataanswer) {
405 if ($dataanswer != "") {
f7ffb898 406 $answer = new stdClass;
5e7856af 407 $answer->lessonid = $question->lessonid;
408 $answer->pageid = $question->id;
409 $answer->jumpto = LESSON_NEXTPAGE;
410 $answer->timecreated = $timenow;
411 $answer->grade = $question->fraction[$key] * 100;
dd192b26 412 $min = $question->answer[$key] - $question->tolerance[$key];
413 $max = $question->answer[$key] + $question->tolerance[$key];
414 $answer->answer = $min.":".$max;
415 // $answer->answer = $question->min[$key].":".$question->max[$key]; original line for min/max
5e7856af 416 $answer->response = $question->feedback[$key];
417 if (!$answer->id = insert_record("lesson_answers", $answer)) {
418 $result->error = "Could not insert numerical quiz answer!";
419 return $result;
420 }
421
422 $answers[] = $answer->id;
423 if ($question->fraction[$key] > $maxfraction) {
424 $maxfraction = $question->fraction[$key];
425 }
426 }
427 }
428
429 /// Perform sanity checks on fractional grades
430 if ($maxfraction != 1) {
431 $maxfraction = $maxfraction * 100;
432 $result->notice = get_string("fractionsnomax", "quiz", $maxfraction);
433 return $result;
434 }
435 break;
436
437
438 case LESSON_TRUEFALSE:
439
440 // the truth
441 $answer->lessonid = $question->lessonid;
442 $answer->pageid = $question->id;
443 $answer->timecreated = $timenow;
444 $answer->answer = get_string("true", "quiz");
445 $answer->grade = $question->answer * 100;
446 if ($answer->grade > 50 ) {
447 $answer->jumpto = LESSON_NEXTPAGE;
448 }
449 if (isset($question->feedbacktrue)) {
450 $answer->response = $question->feedbacktrue;
451 }
452 if (!$true->id = insert_record("lesson_answers", $answer)) {
453 $result->error = "Could not insert quiz answer \"true\")!";
454 return $result;
455 }
456
457 // the lie
f7ffb898 458 $answer = new stdClass;
5e7856af 459 $answer->lessonid = $question->lessonid;
460 $answer->pageid = $question->id;
461 $answer->timecreated = $timenow;
462 $answer->answer = get_string("false", "quiz");
463 $answer->grade = (1 - (int)$question->answer) * 100;
464 if ($answer->grade > 50 ) {
465 $answer->jumpto = LESSON_NEXTPAGE;
466 }
467 if (isset($question->feedbackfalse)) {
468 $answer->response = $question->feedbackfalse;
469 }
470 if (!$false->id = insert_record("lesson_answers", $answer)) {
471 $result->error = "Could not insert quiz answer \"false\")!";
472 return $result;
473 }
474
475 break;
476
477
478 case LESSON_MULTICHOICE:
479
480 $totalfraction = 0;
481 $maxfraction = -1;
482
483 $answers = array();
484
485 // Insert all the new answers
486 foreach ($question->answer as $key => $dataanswer) {
487 if ($dataanswer != "") {
f7ffb898 488 $answer = new stdClass;
5e7856af 489 $answer->lessonid = $question->lessonid;
490 $answer->pageid = $question->id;
491 $answer->timecreated = $timenow;
492 $answer->grade = $question->fraction[$key] * 100;
62eda6ea 493 // changed some defaults
ac8e16be 494 /* Original Code
495 if ($answer->grade > 50 ) {
5e7856af 496 $answer->jumpto = LESSON_NEXTPAGE;
497 }
ac8e16be 498 Replaced with: */
499 if ($answer->grade > 50 ) {
500 $answer->jumpto = LESSON_NEXTPAGE;
5e7856af 501 $answer->score = 1;
502 }
ac8e16be 503 // end Replace
5e7856af 504 $answer->answer = $dataanswer;
505 $answer->response = $question->feedback[$key];
506 if (!$answer->id = insert_record("lesson_answers", $answer)) {
507 $result->error = "Could not insert multichoice quiz answer! ";
508 return $result;
509 }
510 // for Sanity checks
511 if ($question->fraction[$key] > 0) {
512 $totalfraction += $question->fraction[$key];
513 }
514 if ($question->fraction[$key] > $maxfraction) {
515 $maxfraction = $question->fraction[$key];
516 }
517 }
518 }
519
520 /// Perform sanity checks on fractional grades
521 if ($question->single) {
522 if ($maxfraction != 1) {
523 $maxfraction = $maxfraction * 100;
524 $result->notice = get_string("fractionsnomax", "quiz", $maxfraction);
525 return $result;
526 }
527 } else {
528 $totalfraction = round($totalfraction,2);
529 if ($totalfraction != 1) {
530 $totalfraction = $totalfraction * 100;
531 $result->notice = get_string("fractionsaddwrong", "quiz", $totalfraction);
532 return $result;
533 }
534 }
535 break;
536
537 case LESSON_MATCHING:
538
539 $subquestions = array();
540
541 $i = 0;
542 // Insert all the new question+answer pairs
543 foreach ($question->subquestions as $key => $questiontext) {
90455bb3 544 $answertext = $question->subanswers[$key];
5e7856af 545 if (!empty($questiontext) and !empty($answertext)) {
f7ffb898 546 $answer = new stdClass;
5e7856af 547 $answer->lessonid = $question->lessonid;
548 $answer->pageid = $question->id;
549 $answer->timecreated = $timenow;
550 $answer->answer = $questiontext;
551 $answer->response = $answertext;
552 if ($i == 0) {
553 // first answer contains the correct answer jump
554 $answer->jumpto = LESSON_NEXTPAGE;
555 }
556 if (!$subquestion->id = insert_record("lesson_answers", $answer)) {
557 $result->error = "Could not insert quiz match subquestion!";
558 return $result;
559 }
560 $subquestions[] = $subquestion->id;
561 $i++;
562 }
563 }
564
565 if (count($subquestions) < 3) {
566 $result->notice = get_string("notenoughsubquestions", "quiz");
567 return $result;
568 }
569
570 break;
571
572
573 case LESSON_RANDOMSAMATCH:
574 $options->question = $question->id;
575 $options->choose = $question->choose;
576 if ($existing = get_record("quiz_randomsamatch", "question", $options->question)) {
577 $options->id = $existing->id;
578 if (!update_record("quiz_randomsamatch", $options)) {
579 $result->error = "Could not update quiz randomsamatch options!";
580 return $result;
581 }
582 } else {
583 if (!insert_record("quiz_randomsamatch", $options)) {
584 $result->error = "Could not insert quiz randomsamatch options!";
585 return $result;
586 }
587 }
588 break;
589
590 case LESSON_MULTIANSWER:
591 if (!$oldmultianswers = get_records("quiz_multianswers", "question", $question->id, "id ASC")) {
592 $oldmultianswers = array();
593 }
594
595 // Insert all the new multi answers
596 foreach ($question->answers as $dataanswer) {
597 if ($oldmultianswer = array_shift($oldmultianswers)) { // Existing answer, so reuse it
598 $multianswer = $oldmultianswer;
599 $multianswer->positionkey = $dataanswer->positionkey;
600 $multianswer->norm = $dataanswer->norm;
601 $multianswer->answertype = $dataanswer->answertype;
602
603 if (! $multianswer->answers = quiz_save_multianswer_alternatives
604 ($question->id, $dataanswer->answertype,
605 $dataanswer->alternatives, $oldmultianswer->answers))
606 {
607 $result->error = "Could not update multianswer alternatives! (id=$multianswer->id)";
608 return $result;
609 }
610 if (!update_record("quiz_multianswers", $multianswer)) {
611 $result->error = "Could not update quiz multianswer! (id=$multianswer->id)";
612 return $result;
613 }
614 } else { // This is a completely new answer
f7ffb898 615 $multianswer = new stdClass;
5e7856af 616 $multianswer->question = $question->id;
617 $multianswer->positionkey = $dataanswer->positionkey;
618 $multianswer->norm = $dataanswer->norm;
619 $multianswer->answertype = $dataanswer->answertype;
620
621 if (! $multianswer->answers = quiz_save_multianswer_alternatives
622 ($question->id, $dataanswer->answertype,
623 $dataanswer->alternatives))
624 {
625 $result->error = "Could not insert multianswer alternatives! (questionid=$question->id)";
626 return $result;
627 }
628 if (!insert_record("quiz_multianswers", $multianswer)) {
629 $result->error = "Could not insert quiz multianswer!";
630 return $result;
631 }
632 }
633 }
634 break;
635
636 case LESSON_RANDOM:
637 break;
638
639 case LESSON_DESCRIPTION:
640 break;
641
642 default:
643 $result->error = "Unsupported question type ($question->qtype)!";
644 return $result;
645 break;
646 }
647 return true;
648}
4b55d2af 649
650/**
651 * Given an array of value, creates a popup menu to be part of a form.
652 *
653 * @param array $options Used to create the popup menu values ( $options["value"]["label"] ).
654 * @param string $name Name of the select form element.
655 * @param string $selected Current value selected in the popup menu.
656 * @param string $nothing If set, used as the first value in the popup menu.
657 * @param string $script OnChange javascript code.
658 * @param string|int $nothingvalue Value of the $nothing parameter.
659 * @param boolean $return False: Print out the popup menu automatically True: Return the popup menu.
660 * @return string May return the popup menu as a string.
661 * @todo replace the use of this function with choose_from_menu in lib/weblib.php
662 **/
663function lesson_choose_from_menu ($options, $name, $selected="", $nothing="choose", $script="", $nothingvalue="0", $return=false) {
5e7856af 664 if ($nothing == "choose") {
665 $nothing = get_string("choose")."...";
666 }
667
668 if ($script) {
669 $javascript = "onChange=\"$script\"";
670 } else {
671 $javascript = "";
672 }
673
62eda6ea 674 $output = "<label for=$name class=hidden-label>$name</label><SELECT id=$name NAME=$name $javascript>\n";
5e7856af 675 if ($nothing) {
676 $output .= " <OPTION VALUE=\"$nothingvalue\"\n";
677 if ($nothingvalue == $selected) {
678 $output .= " SELECTED";
679 }
680 $output .= ">$nothing</OPTION>\n";
681 }
682 if (!empty($options)) {
683 foreach ($options as $value => $label) {
684 $output .= " <OPTION VALUE=\"$value\"";
685 if ($value == $selected) {
686 $output .= " SELECTED";
687 }
ac8e16be 688 // stop zero label being replaced by array index value
5e7856af 689 // if ($label) {
690 // $output .= ">$label</OPTION>\n";
691 // } else {
692 // $output .= ">$value</OPTION>\n";
ac8e16be 693 // }
694 $output .= ">$label</OPTION>\n";
5e7856af 695
696 }
697 }
698 $output .= "</SELECT>\n";
699
700 if ($return) {
701 return $output;
702 } else {
703 echo $output;
704 }
705}
706
4b55d2af 707/**
708 * Determins if a jumpto value is correct or not.
709 *
710 * returns true if jumpto page is (logically) after the pageid page or
711 * if the jumpto value is a special value. Returns false in all other cases.
712 *
713 * @param int $pageid Id of the page from which you are jumping from.
714 * @param int $jumpto The jumpto number.
715 * @return boolean True or false after a series of tests.
716 * @todo Can be optimized to only have to make 1 or 2 database calls instead of 1 foreach page in the lesson
717 **/
5e7856af 718function lesson_iscorrect($pageid, $jumpto) {
5e7856af 719
720 // first test the special values
721 if (!$jumpto) {
722 // same page
723 return false;
724 } elseif ($jumpto == LESSON_NEXTPAGE) {
725 return true;
ac8e16be 726 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) {
5e7856af 727 return true;
728 } elseif ($jumpto == LESSON_RANDOMPAGE) {
729 return true;
730 } elseif ($jumpto == LESSON_CLUSTERJUMP) {
731 return true;
5e7856af 732 } elseif ($jumpto == LESSON_EOL) {
733 return true;
734 }
735 // we have to run through the pages from pageid looking for jumpid
736 $apageid = get_field("lesson_pages", "nextpageid", "id", $pageid);
737 while (true) {
738 if ($jumpto == $apageid) {
739 return true;
740 }
741 if ($apageid) {
742 $apageid = get_field("lesson_pages", "nextpageid", "id", $apageid);
743 } else {
744 return false;
745 }
746 }
747 return false; // should never be reached
748}
749
4b55d2af 750/**
751 * Checks to see if a page is a branch table or is
752 * a page that is enclosed by a branch table and an end of branch or end of lesson.
753 * May call this function: {@link lesson_is_page_in_branch()}
754 *
755 * @param int $lesson_id Id of the lesson to which the page belongs.
756 * @param int $pageid Id of the page.
757 * @return boolean True or false.
758 * @todo Change $lesson_id param to $lessonid.
759 **/
5e7856af 760function lesson_display_branch_jumps($lesson_id, $pageid) {
ac8e16be 761 if($pageid == 0) {
762 // first page
763 return false;
764 }
765 // get all of the lesson pages
766 if (!$lessonpages = get_records_select("lesson_pages", "lessonid = $lesson_id")) {
767 // adding first page
768 return false;
769 }
770
771 if ($lessonpages[$pageid]->qtype == LESSON_BRANCHTABLE) {
772 return true;
773 }
774
775 return lesson_is_page_in_branch($lessonpages, $pageid);
5e7856af 776}
777
4b55d2af 778/**
779 * Checks to see if a page is a cluster page or is
780 * a page that is enclosed by a cluster page and an end of cluster or end of lesson
781 * May call this function: {@link lesson_is_page_in_cluster()}
782 *
783 * @param int $lesson_id Id of the lesson to which the page belongs.
784 * @param int $pageid Id of the page.
785 * @return boolean True or false.
786 * @todo Change $lesson_id param to $lessonid.
787 **/
5e7856af 788function lesson_display_cluster_jump($lesson_id, $pageid) {
ac8e16be 789 if($pageid == 0) {
790 // first page
791 return false;
792 }
793 // get all of the lesson pages
794 if (!$lessonpages = get_records_select("lesson_pages", "lessonid = $lesson_id")) {
795 // adding first page
796 return false;
797 }
798
799 if ($lessonpages[$pageid]->qtype == LESSON_CLUSTER) {
800 return true;
801 }
802
803 return lesson_is_page_in_cluster($lessonpages, $pageid);
5e7856af 804
805}
806
4b55d2af 807/**
808 * Checks to see if a LESSON_CLUSTERJUMP or
809 * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
810 *
811 * This function is only executed when a teacher is
812 * checking the navigation for a lesson.
813 *
06469639 814 * @param int $lesson Id of the lesson that is to be checked.
4b55d2af 815 * @return boolean True or false.
816 **/
06469639 817function lesson_display_teacher_warning($lesson) {
ac8e16be 818 // get all of the lesson answers
819 if (!$lessonanswers = get_records_select("lesson_answers", "lessonid = $lesson")) {
820 // no answers, then not useing cluster or unseen
821 return false;
822 }
823 // just check for the first one that fulfills the requirements
824 foreach ($lessonanswers as $lessonanswer) {
825 if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
826 return true;
827 }
828 }
829
830 // if no answers use either of the two jumps
831 return false;
5e7856af 832}
833
834
4b55d2af 835/**
836 * Interprets LESSON_CLUSTERJUMP jumpto value.
837 *
838 * This will select a page randomly
839 * and the page selected will be inbetween a cluster page and end of cluter or end of lesson
840 * and the page selected will be a page that has not been viewed already
841 * and if any pages are within a branch table or end of branch then only 1 page within
842 * the branch table or end of branch will be randomly selected (sub clustering).
843 *
844 * @param int $lesson Id of the lesson.
845 * @param int $user Id of the user.
846 * @param int $pageid Id of the current page from which we are jumping from.
847 * @return int The id of the next page.
848 * @todo Change $lesson param to $lessonid and $user param to $userid
849 **/
5e7856af 850function lesson_cluster_jump($lesson, $user, $pageid) {
ac8e16be 851 // get the number of retakes
5e7856af 852 if (!$retakes = count_records("lesson_grades", "lessonid", $lesson, "userid", $user)) {
ac8e16be 853 $retakes = 0;
854 }
855
856 // get all the lesson_attempts aka what the user has seen
857 if ($seen = get_records_select("lesson_attempts", "lessonid = $lesson AND userid = $user AND retry = $retakes", "timeseen DESC")) {
858 foreach ($seen as $value) { // load it into an array that I can more easily use
859 $seenpages[$value->pageid] = $value->pageid;
860 }
861 } else {
862 $seenpages = array();
863 }
864
865 // get the lesson pages
866 if (!$lessonpages = get_records_select("lesson_pages", "lessonid = $lesson")) {
867 error("Error: could not find records in lesson_pages table");
868 }
869 // find the start of the cluster
870 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page
871 if ($lessonpages[$pageid]->qtype == LESSON_CLUSTER) {
872 break;
873 }
874 $pageid = $lessonpages[$pageid]->prevpageid;
875 }
876
877 $pageid = $lessonpages[$pageid]->nextpageid; // move down from the cluster page
878
879 $clusterpages = array();
880 while (true) { // now load all the pages into the cluster that are not already inside of a branch table.
881 if ($lessonpages[$pageid]->qtype == LESSON_ENDOFCLUSTER) {
882 // store the endofcluster page's jump
883 $exitjump = get_field("lesson_answers", "jumpto", "pageid", $pageid, "lessonid", $lesson);
884 if ($exitjump == LESSON_NEXTPAGE) {
885 $exitjump = $lessonpages[$pageid]->nextpageid;
886 }
887 if ($exitjump == 0) {
888 $exitjump = LESSON_EOL;
889 }
890 break;
891 } elseif (!lesson_is_page_in_branch($lessonpages, $pageid) && $lessonpages[$pageid]->qtype != LESSON_ENDOFBRANCH) {
892 // load page into array when it is not in a branch table and when it is not an endofbranch
893 $clusterpages[] = $lessonpages[$pageid];
894 }
895 if ($lessonpages[$pageid]->nextpageid == 0) {
896 // shouldn't ever get here... should be using endofcluster
897 $exitjump = LESSON_EOL;
898 break;
899 } else {
900 $pageid = $lessonpages[$pageid]->nextpageid;
901 }
902 }
903
904 // filter out the ones we have seen
905 $unseen = array();
906 foreach ($clusterpages as $clusterpage) {
907 if ($clusterpage->qtype == LESSON_BRANCHTABLE) { // if branchtable, check to see if any pages inside have been viewed
908 $branchpages = lesson_pages_in_branch($lessonpages, $clusterpage->id); // get the pages in the branchtable
909 $flag = true;
910 foreach ($branchpages as $branchpage) {
911 if (array_key_exists($branchpage->id, $seenpages)) { // check if any of the pages have been viewed
912 $flag = false;
913 }
914 }
915 if ($flag && count($branchpages) > 0) {
916 // add branch table
917 $unseen[] = $clusterpage;
918 }
919 } else {
920 // add any other type of page that has not already been viewed
921 if (!array_key_exists($clusterpage->id, $seenpages)) {
922 $unseen[] = $clusterpage;
923 }
924 }
925 }
926
927 if (count($unseen) > 0) { // it does not contain elements, then use exitjump, otherwise find out next page/branch
928 $nextpage = $unseen[rand(0, count($unseen)-1)];
929 } else {
930 return $exitjump; // seen all there is to see, leave the cluster
931 }
932
933 if ($nextpage->qtype == LESSON_BRANCHTABLE) { // if branch table, then pick a random page inside of it
934 $branchpages = lesson_pages_in_branch($lessonpages, $nextpage->id);
935 return $branchpages[rand(0, count($branchpages)-1)]->id;
936 } else { // otherwise, return the page's id
937 return $nextpage->id;
938 }
5e7856af 939}
940
4b55d2af 941/**
942 * Returns pages that are within a branch table and another branch table, end of branch or end of lesson
943 *
944 * @param array $lessonpages An array of lesson page objects.
945 * @param int $branchid The id of the branch table that we would like the containing pages for.
946 * @return array An array of lesson page objects.
947 **/
5e7856af 948function lesson_pages_in_branch($lessonpages, $branchid) {
ac8e16be 949 $pageid = $lessonpages[$branchid]->nextpageid; // move to the first page after the branch table
950 $pagesinbranch = array();
951
952 while (true) {
953 if ($pageid == 0) { // EOL
954 break;
955 } elseif ($lessonpages[$pageid]->qtype == LESSON_BRANCHTABLE) {
956 break;
957 } elseif ($lessonpages[$pageid]->qtype == LESSON_ENDOFBRANCH) {
958 break;
959 }
960 $pagesinbranch[] = $lessonpages[$pageid];
961 $pageid = $lessonpages[$pageid]->nextpageid;
962 }
963
964 return $pagesinbranch;
5e7856af 965}
966
4b55d2af 967/**
968 * Interprets the LESSON_UNSEENBRANCHPAGE jump.
969 *
970 * will return the pageid of a random unseen page that is within a branch
971 *
972 * @see lesson_pages_in_branch()
973 * @param int $lesson Id of the lesson.
974 * @param int $user Id of the user.
975 * @param int $pageid Id of the page from which we are jumping.
976 * @return int Id of the next page.
977 * @todo Change params $lesson to $lessonid and $user to $userid.
978 **/
5e7856af 979function lesson_unseen_question_jump($lesson, $user, $pageid) {
ac8e16be 980 // get the number of retakes
5e7856af 981 if (!$retakes = count_records("lesson_grades", "lessonid", $lesson, "userid", $user)) {
ac8e16be 982 $retakes = 0;
983 }
984
985 // get all the lesson_attempts aka what the user has seen
986 if ($viewedpages = get_records_select("lesson_attempts", "lessonid = $lesson AND userid = $user AND retry = $retakes", "timeseen DESC")) {
987 foreach($viewedpages as $viewed) {
988 $seenpages[] = $viewed->pageid;
989 }
990 } else {
991 $seenpages = array();
992 }
993
994 // get the lesson pages
995 if (!$lessonpages = get_records_select("lesson_pages", "lessonid = $lesson")) {
996 error("Error: could not find records in lesson_pages table");
997 }
998
999 if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series
1000 $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
1001 }
1002
1003 // go up the pages till branch table
1004 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
1005 if ($lessonpages[$pageid]->qtype == LESSON_BRANCHTABLE) {
1006 break;
1007 }
1008 $pageid = $lessonpages[$pageid]->prevpageid;
1009 }
1010
1011 $pagesinbranch = lesson_pages_in_branch($lessonpages, $pageid);
1012
1013 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
1014 $unseen = array();
1015 foreach($pagesinbranch as $page) {
1016 if (!in_array($page->id, $seenpages)) {
1017 $unseen[] = $page->id;
1018 }
1019 }
1020
1021 if(count($unseen) == 0) {
1022 if(isset($pagesinbranch)) {
1023 $temp = end($pagesinbranch);
1024 $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
1025 } else {
1026 // there are no pages inside the branch, so return the next page
1027 $nextpage = $lessonpages[$pageid]->nextpageid;
1028 }
1029 if ($nextpage == 0) {
1030 return LESSON_EOL;
1031 } else {
1032 return $nextpage;
1033 }
1034 } else {
1035 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
1036 }
5e7856af 1037}
1038
4b55d2af 1039/**
1040 * Handles the unseen branch table jump.
1041 *
1042 * @param int $lesson Lesson id.
1043 * @param int $user User id.
1044 * @return int Will return the page id of a branch table or end of lesson
1045 * @todo Change $lesson param to $lessonid and change $user param to $userid.
1046 **/
5e7856af 1047function lesson_unseen_branch_jump($lesson, $user) {
5e7856af 1048 if (!$retakes = count_records("lesson_grades", "lessonid", $lesson, "userid", $user)) {
ac8e16be 1049 $retakes = 0;
1050 }
1051
1052 if (!$seenbranches = get_records_select("lesson_branch", "lessonid = $lesson AND userid = $user AND retry = $retakes",
1053 "timeseen DESC")) {
1054 error("Error: could not find records in lesson_branch table");
1055 }
1056
1057 // get the lesson pages
1058 if (!$lessonpages = get_records_select("lesson_pages", "lessonid = $lesson")) {
1059 error("Error: could not find records in lesson_pages table");
1060 }
1061
1062 // this loads all the viewed branch tables into $seen untill it finds the branch table with the flag
1063 // which is the branch table that starts the unseenbranch function
1064 $seen = array();
1065 foreach ($seenbranches as $seenbranch) {
1066 if (!$seenbranch->flag) {
1067 $seen[$seenbranch->pageid] = $seenbranch->pageid;
1068 } else {
1069 $start = $seenbranch->pageid;
1070 break;
1071 }
1072 }
1073 // this function searches through the lesson pages to find all the branch tables
1074 // that follow the flagged branch table
1075 $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
1076 while ($pageid != 0) { // grab all of the branch table till eol
1077 if ($lessonpages[$pageid]->qtype == LESSON_BRANCHTABLE) {
1078 $branchtables[] = $lessonpages[$pageid]->id;
1079 }
1080 $pageid = $lessonpages[$pageid]->nextpageid;
1081 }
1082 $unseen = array();
1083 foreach ($branchtables as $branchtable) {
1084 // load all of the unseen branch tables into unseen
1085 if (!array_key_exists($branchtable, $seen)) {
1086 $unseen[] = $branchtable;
1087 }
1088 }
1089 if (count($unseen) > 0) {
1090 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
1091 } else {
1092 return LESSON_EOL; // has viewed all of the branch tables
1093 }
5e7856af 1094}
1095
4b55d2af 1096/**
1097 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
1098 *
1099 * @param int $lesson Lesson id.
1100 * @param int $pageid The id of the page that we are jumping from (?)
1101 * @return int The pageid of a random page that is within a branch table
1102 * @todo Change $lesson param to $lessonid.
1103 **/
5e7856af 1104function lesson_random_question_jump($lesson, $pageid) {
ac8e16be 1105 // get the lesson pages
1106 if (!$lessonpages = get_records_select("lesson_pages", "lessonid = $lesson")) {
1107 error("Error: could not find records in lesson_pages table");
1108 }
1109
1110 // go up the pages till branch table
1111 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
1112
1113 if ($lessonpages[$pageid]->qtype == LESSON_BRANCHTABLE) {
1114 break;
1115 }
1116 $pageid = $lessonpages[$pageid]->prevpageid;
1117 }
1118
1119 // get the pages within the branch
1120 $pagesinbranch = lesson_pages_in_branch($lessonpages, $pageid);
1121
1122 if(count($pagesinbranch) == 0) {
1123 // there are no pages inside the branch, so return the next page
1124 return $lessonpages[$pageid]->nextpageid;
1125 } else {
1126 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
1127 }
5e7856af 1128}
1129
4b55d2af 1130/**
1131 * Check to see if a page is below a branch table (logically).
1132 *
1133 * Will return true if a branch table is found logically above the page.
1134 * Will return false if an end of branch, cluster or the beginning
1135 * of the lesson is found before a branch table.
1136 *
1137 * @param array $pages An array of lesson page objects.
1138 * @param int $pageid Id of the page for testing.
1139 * @return boolean
1140 */
5e7856af 1141function lesson_is_page_in_branch($pages, $pageid) {
ac8e16be 1142 $pageid = $pages[$pageid]->prevpageid; // move up one
1143
1144 // go up the pages till branch table
1145 while (true) {
1146 if ($pageid == 0) { // ran into the beginning of the lesson
1147 return false;
1148 } elseif ($pages[$pageid]->qtype == LESSON_ENDOFBRANCH) { // ran into the end of another branch table
1149 return false;
1150 } elseif ($pages[$pageid]->qtype == LESSON_CLUSTER) { // do not look beyond a cluster
1151 return false;
1152 } elseif ($pages[$pageid]->qtype == LESSON_BRANCHTABLE) { // hit a branch table
1153 return true;
1154 }
1155 $pageid = $pages[$pageid]->prevpageid;
1156 }
5e7856af 1157
1158}
1159
4b55d2af 1160/**
1161 * Check to see if a page is below a cluster page (logically).
1162 *
1163 * Will return true if a cluster is found logically above the page.
1164 * Will return false if an end of cluster or the beginning
1165 * of the lesson is found before a cluster page.
1166 *
1167 * @param array $pages An array of lesson page objects.
1168 * @param int $pageid Id of the page for testing.
1169 * @return boolean
1170 */
5e7856af 1171function lesson_is_page_in_cluster($pages, $pageid) {
ac8e16be 1172 $pageid = $pages[$pageid]->prevpageid; // move up one
1173
1174 // go up the pages till branch table
1175 while (true) {
1176 if ($pageid == 0) { // ran into the beginning of the lesson
1177 return false;
1178 } elseif ($pages[$pageid]->qtype == LESSON_ENDOFCLUSTER) { // ran into the end of another branch table
1179 return false;
1180 } elseif ($pages[$pageid]->qtype == LESSON_CLUSTER) { // hit a branch table
1181 return true;
1182 }
1183 $pageid = $pages[$pageid]->prevpageid;
1184 }
5e7856af 1185}
1186
4b55d2af 1187/**
1188 * Prints the contents for the left menu
1189 *
1190 * Runs through all of the lesson pages and calls {@link lesson_print_tree_link_menu()}
1191 * to print out the link.
1192 *
1193 * @see lesson_print_tree_link_menu()
1194 * @param int $lessonid Lesson id.
1195 * @param int $pageid Page id of the first page of the lesson.
1196 * @param int $id The cmid of the lesson.
1197 * @param boolean $showpages An optional paramater to show question pages as well as branch tables in the left menu (NYI)
1198 * @todo change $id param to $cmid. Finnish implementing the $showpages feature.
1199 * Not necessary to pass $pageid, we can find that out in the function.
1200 * Also, no real need for {@link lesson_print_tree_link_menu()}. Everything can be handled in this function.
1201 */
b9869082 1202function lesson_print_tree_menu($lessonid, $pageid, $id, $showpages=false) {
4b55d2af 1203 if (!$pages = get_records_select("lesson_pages", "lessonid = $lessonid")) {
ac8e16be 1204 error("Error: could not find lesson pages");
1205 }
d6941aff 1206 echo '<ul>';
ac8e16be 1207 while ($pageid != 0) {
1208 lesson_print_tree_link_menu($pages[$pageid], $id, true);
1209 $pageid = $pages[$pageid]->nextpageid;
1210 }
d6941aff 1211 echo '</ul>';
5e7856af 1212}
1213
4b55d2af 1214/**
1215 * Prints the actual link for the left menu
1216 *
1217 * Only prints branch tables that have display set to on.
1218 *
1219 * @param object $page Lesson page object.
1220 * @param int $id The cmid of the lesson.
1221 * @param boolean $showpages An optional paramater to show question pages as well as branch tables in the left menu (NYI)
1222 * @todo change $id param to $cmid. Finnish implementing the $showpages feature.
1223 */
b9869082 1224function lesson_print_tree_link_menu($page, $id, $showpages=false) {
ac8e16be 1225 if ($page->qtype == LESSON_BRANCHTABLE && !$page->display) {
1226 return false;
1227 } elseif ($page->qtype != LESSON_BRANCHTABLE) {
1228 return false;
1229 }
1230
1231 /*elseif ($page->qtype != LESSON_BRANCHTABLE && !$showpages) {
1232 return false;
1233 } elseif (!in_array($page->qtype, $LESSON_QUESTION_TYPE)) {
1234 return false;
1235 }*/
1236
1237 // set up some variables NoticeFix changed whole function
1238 $output = "";
d6941aff 1239 $class = ' class="leftmenu_not_selected_link" ';
ac8e16be 1240
97d2756c 1241 if($page->id == optional_param('pageid', 0, PARAM_INT)) {
1242 $class = ' class="leftmenu_selected_link" ';
1243 }
ac8e16be 1244
d6941aff 1245 $output .= '<li>';
ac8e16be 1246
d6941aff 1247 $output .= "<a $class href=\"view.php?id=$id&amp;action=navigation&amp;pageid=$page->id\">".format_string($page->title,true)."</a>\n";
1248
1249 $output .= "</li>";
5e7856af 1250
d6941aff 1251 echo $output;
5e7856af 1252}
1253
4b55d2af 1254/**
1255 * Prints out the tree view list.
1256 *
1257 * Each page in the lesson is printed out as a link. If the page is a branch table
1258 * or an end of branch then the link color changes and the answer jumps are also printed
1259 * alongside the links. Also, the editing buttons (move, update, delete) are printed
1260 * next to the links.
1261 *
1262 * @uses $USER
a1d0b3eb 1263 * @uses $CFG
4b55d2af 1264 * @param int $pageid Page id of the first page of the lesson.
a1d0b3eb 1265 * @param object $lesson Object of the current lesson.
4b55d2af 1266 * @param int $cmid The course module id of the lesson.
1267 * @param string $pixpath Path to the pictures.
a1d0b3eb 1268 * @todo $pageid does not need to be passed. Can be found in the function.
97d2756c 1269 * This function is only called once. It should be removed and the code inside it moved to view.php
4b55d2af 1270 */
a1d0b3eb 1271function lesson_print_tree($pageid, $lesson, $cmid) {
1272 global $USER, $CFG;
6e1ff5c8 1273 $context = get_context_instance(CONTEXT_MODULE, $cmid);
ac8e16be 1274
a1d0b3eb 1275 if(!$pages = get_records_select("lesson_pages", "lessonid = $lesson->id")) {
ac8e16be 1276 error("Error: could not find lesson pages");
1277 }
1278 echo "<table>";
1279 while ($pageid != 0) {
1280 echo "<tr><td>";
1281 if(($pages[$pageid]->qtype != LESSON_BRANCHTABLE) && ($pages[$pageid]->qtype != LESSON_ENDOFBRANCH)) {
68dfc4de 1282 $output = "<a style='color:#DF041E;' href=\"view.php?id=$cmid&display=".$pages[$pageid]->id."\">".format_string($pages[$pageid]->title,true)."</a>\n";
ac8e16be 1283 } else {
68dfc4de 1284 $output = "<a href=\"view.php?id=$cmid&display=".$pages[$pageid]->id."\">".format_string($pages[$pageid]->title,true)."</a>\n";
ac8e16be 1285
a1d0b3eb 1286 if($answers = get_records_select("lesson_answers", "lessonid = $lesson->id and pageid = $pageid")) {
ac8e16be 1287 $output .= "Jumps to: ";
1288 $end = end($answers);
1289 foreach ($answers as $answer) {
1290 if ($answer->jumpto == 0) {
1291 $output .= get_string("thispage", "lesson");
1292 } elseif ($answer->jumpto == LESSON_NEXTPAGE) {
1293 $output .= get_string("nextpage", "lesson");
1294 } elseif ($answer->jumpto == LESSON_EOL) {
1295 $output .= get_string("endoflesson", "lesson");
1296 } elseif ($answer->jumpto == LESSON_UNSEENBRANCHPAGE) {
1297 $output .= get_string("unseenpageinbranch", "lesson");
1298 } elseif ($answer->jumpto == LESSON_PREVIOUSPAGE) {
1299 $output .= get_string("previouspage", "lesson");
1300 } elseif ($answer->jumpto == LESSON_RANDOMPAGE) {
1301 $output .= get_string("randompageinbranch", "lesson");
1302 } elseif ($answer->jumpto == LESSON_RANDOMBRANCH) {
1303 $output .= get_string("randombranch", "lesson");
1304 } elseif ($answer->jumpto == LESSON_CLUSTERJUMP) {
1305 $output .= get_string("clusterjump", "lesson");
1306 } else {
68dfc4de 1307 $output .= format_string($pages[$answer->jumpto]->title);
ac8e16be 1308 }
1309 if ($answer->id != $end->id) {
1310 $output .= ", ";
1311 }
1312 }
1313 }
1314 }
1315
1316 echo $output;
6e1ff5c8 1317 if (has_capability('mod/lesson:edit', $context)) {
a1d0b3eb 1318 if (count($pages) > 1) {
1319 echo "<a title=\"move\" href=\"lesson.php?id=$cmid&action=move&pageid=".$pages[$pageid]->id."\">\n".
1320 "<img src=\"$CFG->pixpath/t/move.gif\" hspace=\"2\" height=11 width=11 alt=\"move\" border=0></a>\n";
1321 }
1322 echo "<a title=\"update\" href=\"lesson.php?id=$cmid&amp;action=editpage&amp;pageid=".$pages[$pageid]->id."\">\n".
1323 "<img src=\"$CFG->pixpath/t/edit.gif\" hspace=\"2\" height=11 width=11 alt=\"edit\" border=0></a>\n".
1324 "<a title=\"delete\" href=\"lesson.php?id=$cmid&amp;sesskey=".$USER->sesskey."&amp;action=confirmdelete&amp;pageid=".$pages[$pageid]->id."\">\n".
1325 "<img src=\"$CFG->pixpath/t/delete.gif\" hspace=\"2\" height=11 width=11 alt=\"delete\" border=0></a>\n";
ac8e16be 1326 }
ac8e16be 1327 echo "</tr></td>";
1328 $pageid = $pages[$pageid]->nextpageid;
1329 }
1330 echo "</table>";
5e7856af 1331}
1332
4b55d2af 1333/**
1334 * Calculates a user's grade for a lesson.
1335 *
4b55d2af 1336 * @param object $lesson The lesson that the user is taking.
4b55d2af 1337 * @param int $retries The attempt number.
88427c07 1338 * @param int $userid Id of the user (optinal, default current user).
1339 * @return object { nquestions => number of questions answered
1340 attempts => number of question attempts
1341 total => max points possible
1342 earned => points earned by student
1343 grade => calculated percentage grade
1344 nmanual => number of manually graded questions
1345 manualpoints => point value for manually graded questions }
4b55d2af 1346 */
88427c07 1347function lesson_grade($lesson, $ntries, $userid = 0) {
1348 global $USER;
ac8e16be 1349
88427c07 1350 if (empty($userid)) {
1351 $userid = $USER->id;
1352 }
1353
1354 // Zero out everything
1355 $ncorrect = 0;
1356 $nviewed = 0;
1357 $score = 0;
1358 $nmanual = 0;
1359 $manualpoints = 0;
1360 $thegrade = 0;
1361 $nquestions = 0;
1362 $total = 0;
1363 $earned = 0;
1364
1365 if ($useranswers = get_records_select("lesson_attempts", "lessonid = $lesson->id AND
1366 userid = $userid AND retry = $ntries", "timeseen")) {
1367 // group each try with its page
1368 $attemptset = array();
1369 foreach ($useranswers as $useranswer) {
1370 $attemptset[$useranswer->pageid][] = $useranswer;
ac8e16be 1371 }
88427c07 1372
1373 // Drop all attempts that go beyond max attempts for the lesson
1374 foreach ($attemptset as $key => $set) {
1375 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
1376 }
1377
1378 $pageids = implode(",", array_keys($attemptset));
1379
1380 // get only the pages and their answers that the user answered
1381 $pages = get_records_select("lesson_pages", "lessonid = $lesson->id AND id IN($pageids)");
1382 $answers = get_records_select("lesson_answers", "lessonid = $lesson->id AND pageid IN($pageids)");
1383
1384 // Number of pages answered
1385 $nquestions = count($pages);
1386
1387 foreach ($attemptset as $attempts) {
1388 if ($lesson->custom) {
1389 $attempt = end($attempts);
1390 // If essay question, handle it, otherwise add to score
1391 if ($pages[$attempt->pageid]->qtype == LESSON_ESSAY) {
ac8e16be 1392 $essayinfo = unserialize($attempt->useranswer);
88427c07 1393 $earned += $essayinfo->score;
1394 $nmanual++;
1395 $manualpoints += $answers[$attempt->answerid]->score;
ac8e16be 1396 } else {
88427c07 1397 $earned += $answers[$attempt->answerid]->score;
1398 }
1399 } else {
1400 foreach ($attempts as $attempt) {
1401 $earned += $attempt->correct;
1402 }
1403 $attempt = end($attempts); // doesn't matter which one
1404 // If essay question, increase numbers
1405 if ($pages[$attempt->pageid]->qtype == LESSON_ESSAY) {
1406 $nmanual++;
1407 $manualpoints++;
ac8e16be 1408 }
1409 }
88427c07 1410 // Number of times answered
1411 $nviewed += count($attempts);
1412 }
1413
1414 if ($lesson->custom) {
ac8e16be 1415 $bestscores = array();
88427c07 1416 // Find the highest possible score per page to get our total
1417 foreach ($answers as $answer) {
46341ab7 1418 if(!isset($bestscores[$answer->pageid])) {
88427c07 1419 $bestscores[$answer->pageid] = $answer->score;
46341ab7 1420 } else if ($bestscores[$answer->pageid] < $answer->score) {
88427c07 1421 $bestscores[$answer->pageid] = $answer->score;
ac8e16be 1422 }
1423 }
88427c07 1424 $total = array_sum($bestscores);
1425 } else {
1426 // Check to make sure the student has answered the minimum questions
1427 if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
1428 // Nope, increase number viewed by the amount of unanswered questions
1429 $total = $nviewed + ($lesson->minquestions - $nquestions);
1430 } else {
1431 $total = $nviewed;
1432 }
ac8e16be 1433 }
88427c07 1434 }
1435
1436 if ($total) { // not zero
1437 $thegrade = round(100 * $earned / $total, 5);
1438 }
1439
1440 // Build the grade information object
1441 $gradeinfo = new stdClass;
1442 $gradeinfo->nquestions = $nquestions;
1443 $gradeinfo->attempts = $nviewed;
1444 $gradeinfo->total = $total;
1445 $gradeinfo->earned = $earned;
1446 $gradeinfo->grade = $thegrade;
1447 $gradeinfo->nmanual = $nmanual;
1448 $gradeinfo->manualpoints = $manualpoints;
1449
1450 return $gradeinfo;
1451}
1452
1453/**
1454 * Prints the on going message to the user.
1455 *
1456 * With custom grading On, displays points
1457 * earned out of total points possible thus far.
1458 * With custom grading Off, displays number of correct
1459 * answers out of total attempted.
1460 *
1461 * @param object $lesson The lesson that the user is taking.
1462 * @return void
1463 **/
1464function lesson_print_ongoing_score($lesson) {
1465 global $USER;
6e1ff5c8 1466 $cm = get_coursemodule_from_instance('lesson', $lesson->id);
1467 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1468
1469 if (has_capability('mod/lesson:manage', $context)) {
88427c07 1470 echo "<p align=\"center\">".get_string('teacherongoingwarning', 'lesson').'</p>';
1471 } else {
1472 $ntries = count_records("lesson_grades", "lessonid", $lesson->id, "userid", $USER->id);
1473 if (isset($USER->modattempts[$lesson->id])) {
1474 $ntries--;
1475 }
1476 $gradeinfo = lesson_grade($lesson, $ntries);
ac8e16be 1477
88427c07 1478 $a = new stdClass;
1479 if ($lesson->custom) {
1480 $a->score = $gradeinfo->earned;
1481 $a->currenthigh = $gradeinfo->total;
1482 print_simple_box(get_string("ongoingcustom", "lesson", $a), "center");
ac8e16be 1483 } else {
88427c07 1484 $a->correct = $gradeinfo->earned;
1485 $a->viewed = $gradeinfo->attempts;
1486 print_simple_box(get_string("ongoingnormal", "lesson", $a), "center");
ac8e16be 1487 }
1488 }
5e7856af 1489}
1490
4b55d2af 1491/**
1492 * Prints tabs for the editing and adding pages. Each tab is a question type.
1493 *
1494 * @param array $qtypes The question types array (may not need to pass this because it is defined in this file)
1495 * @param string $selected Current selected tab
1496 * @param string $link The base href value of the link for the tab
1497 * @param string $onclick Javascript for the tab link
1498 * @return void
1499 */
5e7856af 1500function lesson_qtype_menu($qtypes, $selected="", $link="", $onclick="") {
271fea97 1501 $tabs = array();
1502 $tabrows = array();
1503
9638a1f4 1504 foreach ($qtypes as $qtype => $qtypename) {
271fea97 1505 $tabrows[] = new tabobject($qtype, "$link&amp;qtype=$qtype\" onClick=\"$onclick\"", $qtypename);
ac8e16be 1506 }
271fea97 1507 $tabs[] = $tabrows;
1508 print_tabs($tabs, $selected);
1509 echo "<input type=\"hidden\" name=\"qtype\" value=\"$selected\" /> \n";
9638a1f4 1510
5e7856af 1511}
1512
4b55d2af 1513/**
1514 * Checks to see if the nickname is naughty or not.
1515 *
1516 * @todo Move this to highscores.php
1517 */
5e7856af 1518function lesson_check_nickname($name) {
5e7856af 1519
832b9f82 1520 if (empty($name)) {
ac8e16be 1521 return false;
1522 }
1523
832b9f82 1524 $filterwords = explode(',', get_string('censorbadwords'));
ac8e16be 1525
1526 foreach ($filterwords as $filterword) {
1527 if (strstr($name, $filterword)) {
1528 return false;
1529 }
1530 }
1531 return true;
5e7856af 1532}
57bfe93d 1533
62eda6ea 1534/**
1535 * Prints out a Progress Bar which depicts a user's progress within a lesson.
1536 *
1537 * Currently works best with a linear lesson. Clusters are counted as a single page.
1538 * Also, only viewed branch tables and questions that have been answered correctly count
1539 * toward lesson completion (or progress). Only Students can see the Progress bar as well.
1540 *
1541 * @param object $lesson The lesson that the user is currently taking.
1542 * @param object $course The course that the to which the lesson belongs.
1543 * @return boolean The return is not significant as of yet. Will return true/false.
1544 * @author Mark Nielsen
1545 **/
1546function lesson_print_progress_bar($lesson, $course) {
1547 global $CFG, $USER;
6e1ff5c8 1548 $cm = get_coursemodule_from_instance('lesson', $lesson->id);
1549 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1550
62eda6ea 1551 // lesson setting to turn progress bar on or off
1552 if (!$lesson->progressbar) {
1553 return false;
1554 }
1555
1556 // catch teachers
6e1ff5c8 1557 if (has_capability('mod/lesson:manage', $context)) {
62eda6ea 1558 notify(get_string('progressbarteacherwarning', 'lesson', $course->teachers));
1559 return false;
1560 }
acab9099 1561 if (!isset($USER->modattempts[$lesson->id])) {
1562 // all of the lesson pages
1563 if (!$pages = get_records('lesson_pages', 'lessonid', $lesson->id)) {
1564 return false;
1565 } else {
1566 foreach ($pages as $page) {
1567 if ($page->prevpageid == 0) {
1568 $pageid = $page->id; // find the first page id
1569 break;
1570 }
62eda6ea 1571 }
1572 }
62eda6ea 1573
acab9099 1574 // current attempt number
1575 if (!$ntries = count_records("lesson_grades", "lessonid", $lesson->id, "userid", $USER->id)) {
1576 $ntries = 0; // may not be necessary
1577 }
62eda6ea 1578
acab9099 1579 $viewedpageids = array();
62eda6ea 1580
acab9099 1581 // collect all of the correctly answered questions
1582 if ($viewedpages = get_records_select("lesson_attempts", "lessonid = $lesson->id AND userid = $USER->id AND retry = $ntries AND correct = 1", 'timeseen DESC', 'pageid, id')) {
1583 $viewedpageids = array_keys($viewedpages);
1584 }
1585 // collect all of the branch tables viewed
1586 if ($viewedbranches = get_records_select("lesson_branch", "lessonid = $lesson->id AND userid = $USER->id AND retry = $ntries", 'timeseen DESC', 'pageid, id')) {
1587 $viewedpageids = array_merge($viewedpageids, array_keys($viewedbranches));
1588 }
1589
1590 // Filter out the following pages:
1591 // End of Cluster
1592 // End of Branch
1593 // Pages found inside of Clusters
1594 // Do not filter out Cluster Page(s) because we count a cluster as one.
1595 // By keeping the cluster page, we get our 1
1596 $validpages = array();
1597 while ($pageid != 0) {
1598 if ($pages[$pageid]->qtype == LESSON_CLUSTER) {
1599 $clusterpageid = $pageid; // copy it
1600 $validpages[$clusterpageid] = 1; // add the cluster page as a valid page
1601 $pageid = $pages[$pageid]->nextpageid; // get next page
62eda6ea 1602
acab9099 1603 // now, remove all necessary viewed paged ids from the viewedpageids array.
1604 while ($pages[$pageid]->qtype != LESSON_ENDOFCLUSTER and $pageid != 0) {
1605 if (in_array($pageid, $viewedpageids)) {
1606 unset($viewedpageids[array_search($pageid, $viewedpageids)]); // remove it
1607 // since the user did see one page in the cluster, add the cluster pageid to the viewedpageids
1608 if (!in_array($clusterpageid, $viewedpageids)) {
1609 $viewedpageids[] = $clusterpageid;
1610 }
62eda6ea 1611 }
acab9099 1612 $pageid = $pages[$pageid]->nextpageid;
62eda6ea 1613 }
acab9099 1614 } elseif ($pages[$pageid]->qtype == LESSON_ENDOFCLUSTER or $pages[$pageid]->qtype == LESSON_ENDOFBRANCH) {
1615 // dont count these, just go to next
1616 $pageid = $pages[$pageid]->nextpageid;
1617 } else {
1618 // a counted page
1619 $validpages[$pageid] = 1;
62eda6ea 1620 $pageid = $pages[$pageid]->nextpageid;
1621 }
acab9099 1622 }
62eda6ea 1623
acab9099 1624 // progress calculation as a percent
1625 $progress = round(count($viewedpageids)/count($validpages), 2) * 100;
1626 } else {
1627 $progress = 100;
1628 }
62eda6ea 1629
1630 // print out the Progress Bar. Attempted to put as much as possible in the style sheets.
1631 echo '<div class="progress_bar" align="center">';
1632 echo '<table class="progress_bar_table"><tr>';
1633 if ($progress != 0) { // some browsers do not repsect the 0 width.
1634 echo '<td width="'.$progress.'%" class="progress_bar_completed">';
1635 echo '</td>';
1636 }
1637 echo '<td class="progress_bar_todo">';
1638 echo '<div class="progress_bar_token"></div>';
1639 echo '</td>';
1640 echo '</tr></table>';
1641 echo '</div>';
1642
1643 return true;
1644}
1645
1646/**
1647 * Determines if a user can view the left menu. The determining factor
1648 * is whether a user has a grade greater than or equal to the lesson setting
1649 * of displayleftif
1650 *
1651 * @param object $lesson Lesson object of the current lesson
1652 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
1653 * @author Mark Nielsen
1654 **/
1655function lesson_displayleftif($lesson) {
1656 global $CFG, $USER;
1657
1658 if (!empty($lesson->displayleftif)) {
1659 // get the current user's max grade for this lesson
1660 if ($maxgrade = get_record_sql('SELECT userid, MAX(grade) AS maxgrade FROM '.$CFG->prefix.'lesson_grades WHERE userid = '.$USER->id.' AND lessonid = '.$lesson->id.' GROUP BY userid')) {
1661 if ($maxgrade->maxgrade < $lesson->displayleftif) {
1662 return 0; // turn off the displayleft
1663 }
1664 } else {
1665 return 0; // no grades
1666 }
1667 }
1668
1669 // if we get to here, keep the original state of displayleft lesson setting
1670 return $lesson->displayleft;
1671}
5e7856af 1672
2a488ba5 1673?>