Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402]
1 <?php 2 3 // This file is part of Moodle - http://moodle.org/ 4 // 5 // Moodle is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // Moodle is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 // 15 // You should have received a copy of the GNU General Public License 16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>. 17 18 /** 19 * Local library file for Lesson. These are non-standard functions that are used 20 * only by Lesson. 21 * 22 * @package mod_lesson 23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} 24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late 25 **/ 26 27 /** Make sure this isn't being directly accessed */ 28 defined('MOODLE_INTERNAL') || die(); 29 30 /** Include the files that are required by this module */ 31 require_once($CFG->dirroot.'/course/moodleform_mod.php'); 32 require_once($CFG->dirroot . '/mod/lesson/lib.php'); 33 require_once($CFG->libdir . '/filelib.php'); 34 35 /** This page */ 36 define('LESSON_THISPAGE', 0); 37 /** Next page -> any page not seen before */ 38 define("LESSON_UNSEENPAGE", 1); 39 /** Next page -> any page not answered correctly */ 40 define("LESSON_UNANSWEREDPAGE", 2); 41 /** Jump to Next Page */ 42 define("LESSON_NEXTPAGE", -1); 43 /** End of Lesson */ 44 define("LESSON_EOL", -9); 45 /** Jump to an unseen page within a branch and end of branch or end of lesson */ 46 define("LESSON_UNSEENBRANCHPAGE", -50); 47 /** Jump to Previous Page */ 48 define("LESSON_PREVIOUSPAGE", -40); 49 /** Jump to a random page within a branch and end of branch or end of lesson */ 50 define("LESSON_RANDOMPAGE", -60); 51 /** Jump to a random Branch */ 52 define("LESSON_RANDOMBRANCH", -70); 53 /** Cluster Jump */ 54 define("LESSON_CLUSTERJUMP", -80); 55 /** Undefined */ 56 define("LESSON_UNDEFINED", -99); 57 58 /** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */ 59 define("LESSON_MAX_EVENT_LENGTH", "432000"); 60 61 /** Answer format is HTML */ 62 define("LESSON_ANSWER_HTML", "HTML"); 63 64 /** Placeholder answer for all other answers. */ 65 define("LESSON_OTHER_ANSWERS", "@#wronganswer#@"); 66 67 ////////////////////////////////////////////////////////////////////////////////////// 68 /// Any other lesson functions go here. Each of them must have a name that 69 /// starts with lesson_ 70 71 /** 72 * Checks to see if a LESSON_CLUSTERJUMP or 73 * a LESSON_UNSEENBRANCHPAGE is used in a lesson. 74 * 75 * This function is only executed when a teacher is 76 * checking the navigation for a lesson. 77 * 78 * @param stdClass $lesson Id of the lesson that is to be checked. 79 * @return boolean True or false. 80 **/ 81 function lesson_display_teacher_warning($lesson) { 82 global $DB; 83 84 // get all of the lesson answers 85 $params = array ("lessonid" => $lesson->id); 86 if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) { 87 // no answers, then not using cluster or unseen 88 return false; 89 } 90 // just check for the first one that fulfills the requirements 91 foreach ($lessonanswers as $lessonanswer) { 92 if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) { 93 return true; 94 } 95 } 96 97 // if no answers use either of the two jumps 98 return false; 99 } 100 101 /** 102 * Interprets the LESSON_UNSEENBRANCHPAGE jump. 103 * 104 * will return the pageid of a random unseen page that is within a branch 105 * 106 * @param lesson $lesson 107 * @param int $userid Id of the user. 108 * @param int $pageid Id of the page from which we are jumping. 109 * @return int Id of the next page. 110 **/ 111 function lesson_unseen_question_jump($lesson, $user, $pageid) { 112 global $DB; 113 114 // get the number of retakes 115 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) { 116 $retakes = 0; 117 } 118 119 // get all the lesson_attempts aka what the user has seen 120 if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) { 121 foreach($viewedpages as $viewed) { 122 $seenpages[] = $viewed->pageid; 123 } 124 } else { 125 $seenpages = array(); 126 } 127 128 // get the lesson pages 129 $lessonpages = $lesson->load_all_pages(); 130 131 if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series 132 $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table 133 } 134 135 // go up the pages till branch table 136 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page 137 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) { 138 break; 139 } 140 $pageid = $lessonpages[$pageid]->prevpageid; 141 } 142 143 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH)); 144 145 // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array 146 $unseen = array(); 147 foreach($pagesinbranch as $page) { 148 if (!in_array($page->id, $seenpages)) { 149 $unseen[] = $page->id; 150 } 151 } 152 153 if(count($unseen) == 0) { 154 if(isset($pagesinbranch)) { 155 $temp = end($pagesinbranch); 156 $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL 157 } else { 158 // there are no pages inside the branch, so return the next page 159 $nextpage = $lessonpages[$pageid]->nextpageid; 160 } 161 if ($nextpage == 0) { 162 return LESSON_EOL; 163 } else { 164 return $nextpage; 165 } 166 } else { 167 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page 168 } 169 } 170 171 /** 172 * Handles the unseen branch table jump. 173 * 174 * @param lesson $lesson 175 * @param int $userid User id. 176 * @return int Will return the page id of a branch table or end of lesson 177 **/ 178 function lesson_unseen_branch_jump($lesson, $userid) { 179 global $DB; 180 181 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) { 182 $retakes = 0; 183 } 184 185 if (!$seenbranches = $lesson->get_content_pages_viewed($retakes, $userid, 'timeseen DESC')) { 186 throw new \moodle_exception('cannotfindrecords', 'lesson'); 187 } 188 189 // get the lesson pages 190 $lessonpages = $lesson->load_all_pages(); 191 192 // this loads all the viewed branch tables into $seen until it finds the branch table with the flag 193 // which is the branch table that starts the unseenbranch function 194 $seen = array(); 195 foreach ($seenbranches as $seenbranch) { 196 if (!$seenbranch->flag) { 197 $seen[$seenbranch->pageid] = $seenbranch->pageid; 198 } else { 199 $start = $seenbranch->pageid; 200 break; 201 } 202 } 203 // this function searches through the lesson pages to find all the branch tables 204 // that follow the flagged branch table 205 $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table 206 $branchtables = array(); 207 while ($pageid != 0) { // grab all of the branch table till eol 208 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) { 209 $branchtables[] = $lessonpages[$pageid]->id; 210 } 211 $pageid = $lessonpages[$pageid]->nextpageid; 212 } 213 $unseen = array(); 214 foreach ($branchtables as $branchtable) { 215 // load all of the unseen branch tables into unseen 216 if (!array_key_exists($branchtable, $seen)) { 217 $unseen[] = $branchtable; 218 } 219 } 220 if (count($unseen) > 0) { 221 return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page 222 } else { 223 return LESSON_EOL; // has viewed all of the branch tables 224 } 225 } 226 227 /** 228 * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE). 229 * 230 * @param lesson $lesson 231 * @param int $pageid The id of the page that we are jumping from (?) 232 * @return int The pageid of a random page that is within a branch table 233 **/ 234 function lesson_random_question_jump($lesson, $pageid) { 235 global $DB; 236 237 // get the lesson pages 238 $params = array ("lessonid" => $lesson->id); 239 if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) { 240 throw new \moodle_exception('cannotfindpages', 'lesson'); 241 } 242 243 // go up the pages till branch table 244 while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page 245 246 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) { 247 break; 248 } 249 $pageid = $lessonpages[$pageid]->prevpageid; 250 } 251 252 // get the pages within the branch 253 $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH)); 254 255 if(count($pagesinbranch) == 0) { 256 // there are no pages inside the branch, so return the next page 257 return $lessonpages[$pageid]->nextpageid; 258 } else { 259 return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page 260 } 261 } 262 263 /** 264 * Calculates a user's grade for a lesson. 265 * 266 * @param object $lesson The lesson that the user is taking. 267 * @param int $retries The attempt number. 268 * @param int $userid Id of the user (optional, default current user). 269 * @return object { nquestions => number of questions answered 270 attempts => number of question attempts 271 total => max points possible 272 earned => points earned by student 273 grade => calculated percentage grade 274 nmanual => number of manually graded questions 275 manualpoints => point value for manually graded questions } 276 */ 277 function lesson_grade($lesson, $ntries, $userid = 0) { 278 global $USER, $DB; 279 280 if (empty($userid)) { 281 $userid = $USER->id; 282 } 283 284 // Zero out everything 285 $ncorrect = 0; 286 $nviewed = 0; 287 $score = 0; 288 $nmanual = 0; 289 $manualpoints = 0; 290 $thegrade = 0; 291 $nquestions = 0; 292 $total = 0; 293 $earned = 0; 294 295 $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries); 296 if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND 297 userid = :userid AND retry = :retry", $params, "timeseen")) { 298 // group each try with its page 299 $attemptset = array(); 300 foreach ($useranswers as $useranswer) { 301 $attemptset[$useranswer->pageid][] = $useranswer; 302 } 303 304 if (!empty($lesson->maxattempts)) { 305 // Drop all attempts that go beyond max attempts for the lesson. 306 foreach ($attemptset as $key => $set) { 307 $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts); 308 } 309 } 310 311 // get only the pages and their answers that the user answered 312 list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset)); 313 array_unshift($parameters, $lesson->id); 314 $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters); 315 $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters); 316 317 // Number of pages answered 318 $nquestions = count($pages); 319 320 foreach ($attemptset as $attempts) { 321 $page = lesson_page::load($pages[end($attempts)->pageid], $lesson); 322 if ($lesson->custom) { 323 $attempt = end($attempts); 324 // If essay question, handle it, otherwise add to score 325 if ($page->requires_manual_grading()) { 326 $useranswerobj = unserialize_object($attempt->useranswer); 327 if (isset($useranswerobj->score)) { 328 $earned += $useranswerobj->score; 329 } 330 $nmanual++; 331 $manualpoints += $answers[$attempt->answerid]->score; 332 } else if (!empty($attempt->answerid)) { 333 $earned += $page->earned_score($answers, $attempt); 334 } 335 } else { 336 foreach ($attempts as $attempt) { 337 $earned += $attempt->correct; 338 } 339 $attempt = end($attempts); // doesn't matter which one 340 // If essay question, increase numbers 341 if ($page->requires_manual_grading()) { 342 $nmanual++; 343 $manualpoints++; 344 } 345 } 346 // Number of times answered 347 $nviewed += count($attempts); 348 } 349 350 if ($lesson->custom) { 351 $bestscores = array(); 352 // Find the highest possible score per page to get our total 353 foreach ($answers as $answer) { 354 if(!isset($bestscores[$answer->pageid])) { 355 $bestscores[$answer->pageid] = $answer->score; 356 } else if ($bestscores[$answer->pageid] < $answer->score) { 357 $bestscores[$answer->pageid] = $answer->score; 358 } 359 } 360 $total = array_sum($bestscores); 361 } else { 362 // Check to make sure the student has answered the minimum questions 363 if ($lesson->minquestions and $nquestions < $lesson->minquestions) { 364 // Nope, increase number viewed by the amount of unanswered questions 365 $total = $nviewed + ($lesson->minquestions - $nquestions); 366 } else { 367 $total = $nviewed; 368 } 369 } 370 } 371 372 if ($total) { // not zero 373 $thegrade = round(100 * $earned / $total, 5); 374 } 375 376 // Build the grade information object 377 $gradeinfo = new stdClass; 378 $gradeinfo->nquestions = $nquestions; 379 $gradeinfo->attempts = $nviewed; 380 $gradeinfo->total = $total; 381 $gradeinfo->earned = $earned; 382 $gradeinfo->grade = $thegrade; 383 $gradeinfo->nmanual = $nmanual; 384 $gradeinfo->manualpoints = $manualpoints; 385 386 return $gradeinfo; 387 } 388 389 /** 390 * Determines if a user can view the left menu. The determining factor 391 * is whether a user has a grade greater than or equal to the lesson setting 392 * of displayleftif 393 * 394 * @param object $lesson Lesson object of the current lesson 395 * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged 396 **/ 397 function lesson_displayleftif($lesson) { 398 global $CFG, $USER, $DB; 399 400 if (!empty($lesson->displayleftif)) { 401 // get the current user's max grade for this lesson 402 $params = array ("userid" => $USER->id, "lessonid" => $lesson->id); 403 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)) { 404 if ($maxgrade->maxgrade < $lesson->displayleftif) { 405 return 0; // turn off the displayleft 406 } 407 } else { 408 return 0; // no grades 409 } 410 } 411 412 // if we get to here, keep the original state of displayleft lesson setting 413 return $lesson->displayleft; 414 } 415 416 /** 417 * 418 * @param $cm 419 * @param $lesson 420 * @param $page 421 * @return unknown_type 422 */ 423 function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) { 424 $bc = lesson_menu_block_contents($cm->id, $lesson); 425 if (!empty($bc)) { 426 $regions = $page->blocks->get_regions(); 427 $firstregion = reset($regions); 428 $page->blocks->add_fake_block($bc, $firstregion); 429 } 430 431 $bc = lesson_mediafile_block_contents($cm->id, $lesson); 432 if (!empty($bc)) { 433 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region()); 434 } 435 436 if (!empty($timer)) { 437 $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page); 438 if (!empty($bc)) { 439 $page->blocks->add_fake_block($bc, $page->blocks->get_default_region()); 440 } 441 } 442 } 443 444 /** 445 * If there is a media file associated with this 446 * lesson, return a block_contents that displays it. 447 * 448 * @param int $cmid Course Module ID for this lesson 449 * @param object $lesson Full lesson record object 450 * @return block_contents 451 **/ 452 function lesson_mediafile_block_contents($cmid, $lesson) { 453 global $OUTPUT; 454 if (empty($lesson->mediafile)) { 455 return null; 456 } 457 458 $options = array(); 459 $options['menubar'] = 0; 460 $options['location'] = 0; 461 $options['left'] = 5; 462 $options['top'] = 5; 463 $options['scrollbars'] = 1; 464 $options['resizable'] = 1; 465 $options['width'] = $lesson->mediawidth; 466 $options['height'] = $lesson->mediaheight; 467 468 $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid); 469 $action = new popup_action('click', $link, 'lessonmediafile', $options); 470 $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson'))); 471 472 $bc = new block_contents(); 473 $bc->title = get_string('linkedmedia', 'lesson'); 474 $bc->attributes['class'] = 'mediafile block'; 475 $bc->content = $content; 476 477 return $bc; 478 } 479 480 /** 481 * If a timed lesson and not a teacher, then 482 * return a block_contents containing the clock. 483 * 484 * @param int $cmid Course Module ID for this lesson 485 * @param object $lesson Full lesson record object 486 * @param object $timer Full timer record object 487 * @return block_contents 488 **/ 489 function lesson_clock_block_contents($cmid, $lesson, $timer, $page) { 490 // Display for timed lessons and for students only 491 $context = context_module::instance($cmid); 492 if ($lesson->timelimit == 0 || has_capability('mod/lesson:manage', $context)) { 493 return null; 494 } 495 496 $content = '<div id="lesson-timer">'; 497 $content .= $lesson->time_remaining($timer->starttime); 498 $content .= '</div>'; 499 500 $clocksettings = array('starttime' => $timer->starttime, 'servertime' => time(), 'testlength' => $lesson->timelimit); 501 $page->requires->data_for_js('clocksettings', $clocksettings, true); 502 $page->requires->strings_for_js(array('timeisup'), 'lesson'); 503 $page->requires->js('/mod/lesson/timer.js'); 504 $page->requires->js_init_call('show_clock'); 505 506 $bc = new block_contents(); 507 $bc->title = get_string('timeremaining', 'lesson'); 508 $bc->attributes['class'] = 'clock block'; 509 $bc->content = $content; 510 511 return $bc; 512 } 513 514 /** 515 * If left menu is turned on, then this will 516 * print the menu in a block 517 * 518 * @param int $cmid Course Module ID for this lesson 519 * @param lesson $lesson Full lesson record object 520 * @return void 521 **/ 522 function lesson_menu_block_contents($cmid, $lesson) { 523 global $CFG, $DB; 524 525 if (!$lesson->displayleft) { 526 return null; 527 } 528 529 $pages = $lesson->load_all_pages(); 530 foreach ($pages as $page) { 531 if ((int)$page->prevpageid === 0) { 532 $pageid = $page->id; 533 break; 534 } 535 } 536 $currentpageid = optional_param('pageid', $pageid, PARAM_INT); 537 538 if (!$pageid || !$pages) { 539 return null; 540 } 541 542 $content = '<a href="#maincontent" class="accesshide">' . 543 get_string('skip', 'lesson') . 544 "</a>\n<div class=\"menuwrapper\">\n<ul>\n"; 545 546 while ($pageid != 0) { 547 $page = $pages[$pageid]; 548 549 // Only process branch tables with display turned on 550 if ($page->displayinmenublock && $page->display) { 551 if ($page->id == $currentpageid) { 552 $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n"; 553 } else { 554 $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"; 555 } 556 557 } 558 $pageid = $page->nextpageid; 559 } 560 $content .= "</ul>\n</div>\n"; 561 562 $bc = new block_contents(); 563 $bc->title = get_string('lessonmenu', 'lesson'); 564 $bc->attributes['class'] = 'menu block'; 565 $bc->content = $content; 566 567 return $bc; 568 } 569 570 /** 571 * Adds header buttons to the page for the lesson 572 * 573 * @deprecated since Moodle 4.0 in favour of tertiary navigation. 574 * @todo MDL-73545 This will be deleted in Moodle 4.4 575 * @param object $cm 576 * @param object $context 577 * @param bool $extraeditbuttons 578 * @param int $lessonpageid 579 */ 580 function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) { 581 global $CFG, $PAGE, $OUTPUT; 582 583 debugging('lesson_add_header_buttons() is deprecated in favour of tertiary navigation.', DEBUG_DEVELOPER); 584 585 if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) { 586 if ($lessonpageid === null) { 587 throw new \moodle_exception('invalidpageid', 'lesson'); 588 } 589 if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) { 590 $url = new moodle_url('/mod/lesson/editpage.php', array( 591 'id' => $cm->id, 592 'pageid' => $lessonpageid, 593 'edit' => 1, 594 'returnto' => $PAGE->url->out_as_local_url(false) 595 )); 596 $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson'))); 597 } 598 } 599 } 600 601 /** 602 * This is a function used to detect media types and generate html code. 603 * 604 * @global object $CFG 605 * @global object $PAGE 606 * @param object $lesson 607 * @param object $context 608 * @return string $code the html code of media 609 */ 610 function lesson_get_media_html($lesson, $context) { 611 global $CFG, $PAGE, $OUTPUT; 612 require_once("$CFG->libdir/resourcelib.php"); 613 614 // get the media file link 615 if (strpos($lesson->mediafile, '://') !== false) { 616 $url = new moodle_url($lesson->mediafile); 617 } else { 618 // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder 619 $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/')); 620 } 621 $title = $lesson->mediafile; 622 623 $clicktoopen = html_writer::link($url, get_string('download')); 624 625 $mimetype = resourcelib_guess_url_mimetype($url); 626 627 $extension = resourcelib_get_extension($url->out(false)); 628 629 $mediamanager = core_media_manager::instance($PAGE); 630 $embedoptions = array( 631 core_media_manager::OPTION_TRUSTED => true, 632 core_media_manager::OPTION_BLOCK => true 633 ); 634 635 // find the correct type and print it out 636 if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image 637 $code = resourcelib_embed_image($url, $title); 638 639 } else if ($mediamanager->can_embed_url($url, $embedoptions)) { 640 // Media (audio/video) file. 641 $code = $mediamanager->embed_url($url, $title, 0, 0, $embedoptions); 642 643 } else { 644 // anything else - just try object tag enlarged as much as possible 645 $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype); 646 } 647 648 return $code; 649 } 650 651 /** 652 * Logic to happen when a/some group(s) has/have been deleted in a course. 653 * 654 * @param int $courseid The course ID. 655 * @param int $groupid The group id if it is known 656 * @return void 657 */ 658 function lesson_process_group_deleted_in_course($courseid, $groupid = null) { 659 global $DB; 660 661 $params = array('courseid' => $courseid); 662 if ($groupid) { 663 $params['groupid'] = $groupid; 664 // We just update the group that was deleted. 665 $sql = "SELECT o.id, o.lessonid, o.groupid 666 FROM {lesson_overrides} o 667 JOIN {lesson} lesson ON lesson.id = o.lessonid 668 WHERE lesson.course = :courseid 669 AND o.groupid = :groupid"; 670 } else { 671 // No groupid, we update all orphaned group overrides for all lessons in course. 672 $sql = "SELECT o.id, o.lessonid, o.groupid 673 FROM {lesson_overrides} o 674 JOIN {lesson} lesson ON lesson.id = o.lessonid 675 LEFT JOIN {groups} grp ON grp.id = o.groupid 676 WHERE lesson.course = :courseid 677 AND o.groupid IS NOT NULL 678 AND grp.id IS NULL"; 679 } 680 $records = $DB->get_records_sql($sql, $params); 681 if (!$records) { 682 return; // Nothing to do. 683 } 684 $DB->delete_records_list('lesson_overrides', 'id', array_keys($records)); 685 $cache = cache::make('mod_lesson', 'overrides'); 686 foreach ($records as $record) { 687 $cache->delete("{$record->lessonid}_g_{$record->groupid}"); 688 } 689 } 690 691 /** 692 * Return the overview report table and data. 693 * 694 * @param lesson $lesson lesson instance 695 * @param mixed $currentgroup false if not group used, 0 for all groups, group id (int) to filter by that groups 696 * @return mixed false if there is no information otherwise html_table and stdClass with the table and data 697 * @since Moodle 3.3 698 */ 699 function lesson_get_overview_report_table_and_data(lesson $lesson, $currentgroup) { 700 global $DB, $CFG, $OUTPUT; 701 require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php'); 702 703 $context = $lesson->context; 704 $cm = $lesson->cm; 705 // Count the number of branch and question pages in this lesson. 706 $branchcount = $DB->count_records('lesson_pages', array('lessonid' => $lesson->id, 'qtype' => LESSON_PAGE_BRANCHTABLE)); 707 $questioncount = ($DB->count_records('lesson_pages', array('lessonid' => $lesson->id)) - $branchcount); 708 709 // Only load students if there attempts for this lesson. 710 $attempts = $DB->record_exists('lesson_attempts', array('lessonid' => $lesson->id)); 711 $branches = $DB->record_exists('lesson_branch', array('lessonid' => $lesson->id)); 712 $timer = $DB->record_exists('lesson_timer', array('lessonid' => $lesson->id)); 713 if ($attempts or $branches or $timer) { 714 list($esql, $params) = get_enrolled_sql($context, '', $currentgroup, true); 715 list($sort, $sortparams) = users_order_by_sql('u'); 716 717 // TODO Does not support custom user profile fields (MDL-70456). 718 $userfieldsapi = \core_user\fields::for_identity($context, false)->with_userpic(); 719 $ufields = $userfieldsapi->get_sql('u', false, '', '', false)->selects; 720 $extrafields = $userfieldsapi->get_required_fields([\core_user\fields::PURPOSE_IDENTITY]); 721 722 $params['a1lessonid'] = $lesson->id; 723 $params['b1lessonid'] = $lesson->id; 724 $params['c1lessonid'] = $lesson->id; 725 $sql = "SELECT DISTINCT $ufields 726 FROM {user} u 727 JOIN ( 728 SELECT userid, lessonid FROM {lesson_attempts} a1 729 WHERE a1.lessonid = :a1lessonid 730 UNION 731 SELECT userid, lessonid FROM {lesson_branch} b1 732 WHERE b1.lessonid = :b1lessonid 733 UNION 734 SELECT userid, lessonid FROM {lesson_timer} c1 735 WHERE c1.lessonid = :c1lessonid 736 ) a ON u.id = a.userid 737 JOIN ($esql) ue ON ue.id = a.userid 738 ORDER BY $sort"; 739 740 $students = $DB->get_recordset_sql($sql, $params); 741 if (!$students->valid()) { 742 $students->close(); 743 return array(false, false); 744 } 745 } else { 746 return array(false, false); 747 } 748 749 if (! $grades = $DB->get_records('lesson_grades', array('lessonid' => $lesson->id), 'completed')) { 750 $grades = array(); 751 } 752 753 if (! $times = $DB->get_records('lesson_timer', array('lessonid' => $lesson->id), 'starttime')) { 754 $times = array(); 755 } 756 757 // Build an array for output. 758 $studentdata = array(); 759 760 $attempts = $DB->get_recordset('lesson_attempts', array('lessonid' => $lesson->id), 'timeseen'); 761 foreach ($attempts as $attempt) { 762 // if the user is not in the array or if the retry number is not in the sub array, add the data for that try. 763 if (empty($studentdata[$attempt->userid]) || empty($studentdata[$attempt->userid][$attempt->retry])) { 764 // restore/setup defaults 765 $n = 0; 766 $timestart = 0; 767 $timeend = 0; 768 $usergrade = null; 769 $eol = 0; 770 771 // search for the grade record for this try. if not there, the nulls defined above will be used. 772 foreach($grades as $grade) { 773 // check to see if the grade matches the correct user 774 if ($grade->userid == $attempt->userid) { 775 // see if n is = to the retry 776 if ($n == $attempt->retry) { 777 // get grade info 778 $usergrade = round($grade->grade, 2); // round it here so we only have to do it once 779 break; 780 } 781 $n++; // if not equal, then increment n 782 } 783 } 784 $n = 0; 785 // search for the time record for this try. if not there, the nulls defined above will be used. 786 foreach($times as $time) { 787 // check to see if the grade matches the correct user 788 if ($time->userid == $attempt->userid) { 789 // see if n is = to the retry 790 if ($n == $attempt->retry) { 791 // get grade info 792 $timeend = $time->lessontime; 793 $timestart = $time->starttime; 794 $eol = $time->completed; 795 break; 796 } 797 $n++; // if not equal, then increment n 798 } 799 } 800 801 // build up the array. 802 // this array represents each student and all of their tries at the lesson 803 $studentdata[$attempt->userid][$attempt->retry] = array( "timestart" => $timestart, 804 "timeend" => $timeend, 805 "grade" => $usergrade, 806 "end" => $eol, 807 "try" => $attempt->retry, 808 "userid" => $attempt->userid); 809 } 810 } 811 $attempts->close(); 812 813 $branches = $DB->get_recordset('lesson_branch', array('lessonid' => $lesson->id), 'timeseen'); 814 foreach ($branches as $branch) { 815 // If the user is not in the array or if the retry number is not in the sub array, add the data for that try. 816 if (empty($studentdata[$branch->userid]) || empty($studentdata[$branch->userid][$branch->retry])) { 817 // Restore/setup defaults. 818 $n = 0; 819 $timestart = 0; 820 $timeend = 0; 821 $usergrade = null; 822 $eol = 0; 823 // Search for the time record for this try. if not there, the nulls defined above will be used. 824 foreach ($times as $time) { 825 // Check to see if the grade matches the correct user. 826 if ($time->userid == $branch->userid) { 827 // See if n is = to the retry. 828 if ($n == $branch->retry) { 829 // Get grade info. 830 $timeend = $time->lessontime; 831 $timestart = $time->starttime; 832 $eol = $time->completed; 833 break; 834 } 835 $n++; // If not equal, then increment n. 836 } 837 } 838 839 // Build up the array. 840 // This array represents each student and all of their tries at the lesson. 841 $studentdata[$branch->userid][$branch->retry] = array( "timestart" => $timestart, 842 "timeend" => $timeend, 843 "grade" => $usergrade, 844 "end" => $eol, 845 "try" => $branch->retry, 846 "userid" => $branch->userid); 847 } 848 } 849 $branches->close(); 850 851 // Need the same thing for timed entries that were not completed. 852 foreach ($times as $time) { 853 $endoflesson = $time->completed; 854 // If the time start is the same with another record then we shouldn't be adding another item to this array. 855 if (isset($studentdata[$time->userid])) { 856 $foundmatch = false; 857 $n = 0; 858 foreach ($studentdata[$time->userid] as $key => $value) { 859 if ($value['timestart'] == $time->starttime) { 860 // Don't add this to the array. 861 $foundmatch = true; 862 break; 863 } 864 } 865 $n = count($studentdata[$time->userid]) + 1; 866 if (!$foundmatch) { 867 // Add a record. 868 $studentdata[$time->userid][] = array( 869 "timestart" => $time->starttime, 870 "timeend" => $time->lessontime, 871 "grade" => null, 872 "end" => $endoflesson, 873 "try" => $n, 874 "userid" => $time->userid 875 ); 876 } 877 } else { 878 $studentdata[$time->userid][] = array( 879 "timestart" => $time->starttime, 880 "timeend" => $time->lessontime, 881 "grade" => null, 882 "end" => $endoflesson, 883 "try" => 0, 884 "userid" => $time->userid 885 ); 886 } 887 } 888 889 // To store all the data to be returned by the function. 890 $data = new stdClass(); 891 892 // Determine if lesson should have a score. 893 if ($branchcount > 0 AND $questioncount == 0) { 894 // This lesson only contains content pages and is not graded. 895 $data->lessonscored = false; 896 } else { 897 // This lesson is graded. 898 $data->lessonscored = true; 899 } 900 // set all the stats variables 901 $data->numofattempts = 0; 902 $data->avescore = 0; 903 $data->avetime = 0; 904 $data->highscore = null; 905 $data->lowscore = null; 906 $data->hightime = null; 907 $data->lowtime = null; 908 $data->students = array(); 909 910 $table = new html_table(); 911 912 $headers = [get_string('name')]; 913 914 foreach ($extrafields as $field) { 915 $headers[] = \core_user\fields::get_display_name($field); 916 } 917 918 $caneditlesson = has_capability('mod/lesson:edit', $context); 919 $attemptsheader = get_string('attempts', 'lesson'); 920 if ($caneditlesson) { 921 $selectall = get_string('selectallattempts', 'lesson'); 922 $deselectall = get_string('deselectallattempts', 'lesson'); 923 // Build the select/deselect all control. 924 $selectallid = 'selectall-attempts'; 925 $mastercheckbox = new \core\output\checkbox_toggleall('lesson-attempts', true, [ 926 'id' => $selectallid, 927 'name' => $selectallid, 928 'value' => 1, 929 'label' => $selectall, 930 'selectall' => $selectall, 931 'deselectall' => $deselectall, 932 'labelclasses' => 'form-check-label' 933 ]); 934 $attemptsheader = $OUTPUT->render($mastercheckbox); 935 } 936 $headers [] = $attemptsheader; 937 938 // Set up the table object. 939 if ($data->lessonscored) { 940 $headers [] = get_string('highscore', 'lesson'); 941 } 942 943 $colcount = count($headers); 944 945 $table->head = $headers; 946 947 $table->align = []; 948 $table->align = array_pad($table->align, $colcount, 'center'); 949 $table->align[$colcount - 1] = 'left'; 950 951 if ($data->lessonscored) { 952 $table->align[$colcount - 2] = 'left'; 953 } 954 955 $table->attributes['class'] = 'table table-striped'; 956 957 // print out the $studentdata array 958 // going through each student that has attempted the lesson, so, each student should have something to be displayed 959 foreach ($students as $student) { 960 // check to see if the student has attempts to print out 961 if (array_key_exists($student->id, $studentdata)) { 962 // set/reset some variables 963 $attempts = array(); 964 $dataforstudent = new stdClass; 965 $dataforstudent->attempts = array(); 966 // gather the data for each user attempt 967 $bestgrade = 0; 968 969 // $tries holds all the tries/retries a student has done 970 $tries = $studentdata[$student->id]; 971 $studentname = fullname($student, true); 972 973 foreach ($tries as $try) { 974 $dataforstudent->attempts[] = $try; 975 976 // Start to build up the checkbox and link. 977 $attempturlparams = [ 978 'id' => $cm->id, 979 'action' => 'reportdetail', 980 'userid' => $try['userid'], 981 'try' => $try['try'], 982 ]; 983 984 if ($try["grade"] !== null) { // if null then not done yet 985 // this is what the link does when the user has completed the try 986 $timetotake = $try["timeend"] - $try["timestart"]; 987 988 if ($try["grade"] > $bestgrade) { 989 $bestgrade = $try["grade"]; 990 } 991 992 $attemptdata = (object)[ 993 'grade' => $try["grade"], 994 'timestart' => userdate($try["timestart"]), 995 'duration' => format_time($timetotake), 996 ]; 997 $attemptlinkcontents = get_string('attemptinfowithgrade', 'lesson', $attemptdata); 998 999 } else { 1000 if ($try["end"]) { 1001 // User finished the lesson but has no grade. (Happens when there are only content pages). 1002 $timetotake = $try["timeend"] - $try["timestart"]; 1003 $attemptdata = (object)[ 1004 'timestart' => userdate($try["timestart"]), 1005 'duration' => format_time($timetotake), 1006 ]; 1007 $attemptlinkcontents = get_string('attemptinfonograde', 'lesson', $attemptdata); 1008 } else { 1009 // This is what the link does/looks like when the user has not completed the attempt. 1010 if ($try['timestart'] !== 0) { 1011 // Teacher previews do not track time spent. 1012 $attemptlinkcontents = get_string("notcompletedwithdate", "lesson", userdate($try["timestart"])); 1013 } else { 1014 $attemptlinkcontents = get_string("notcompleted", "lesson"); 1015 } 1016 $timetotake = null; 1017 } 1018 } 1019 $attempturl = new moodle_url('/mod/lesson/report.php', $attempturlparams); 1020 $attemptlink = html_writer::link($attempturl, $attemptlinkcontents, ['class' => 'lesson-attempt-link']); 1021 1022 if ($caneditlesson) { 1023 $attemptid = 'attempt-' . $try['userid'] . '-' . $try['try']; 1024 $attemptname = 'attempts[' . $try['userid'] . '][' . $try['try'] . ']'; 1025 1026 $checkbox = new \core\output\checkbox_toggleall('lesson-attempts', false, [ 1027 'id' => $attemptid, 1028 'name' => $attemptname, 1029 'label' => $attemptlink 1030 ]); 1031 $attemptlink = $OUTPUT->render($checkbox); 1032 } 1033 1034 // build up the attempts array 1035 $attempts[] = $attemptlink; 1036 1037 // Run these lines for the stats only if the user finnished the lesson. 1038 if ($try["end"]) { 1039 // User has completed the lesson. 1040 $data->numofattempts++; 1041 $data->avetime += $timetotake; 1042 if ($timetotake > $data->hightime || $data->hightime == null) { 1043 $data->hightime = $timetotake; 1044 } 1045 if ($timetotake < $data->lowtime || $data->lowtime == null) { 1046 $data->lowtime = $timetotake; 1047 } 1048 if ($try["grade"] !== null) { 1049 // The lesson was scored. 1050 $data->avescore += $try["grade"]; 1051 if ($try["grade"] > $data->highscore || $data->highscore === null) { 1052 $data->highscore = $try["grade"]; 1053 } 1054 if ($try["grade"] < $data->lowscore || $data->lowscore === null) { 1055 $data->lowscore = $try["grade"]; 1056 } 1057 1058 } 1059 } 1060 } 1061 // get line breaks in after each attempt 1062 $attempts = implode("<br />\n", $attempts); 1063 $row = [$studentname]; 1064 1065 foreach ($extrafields as $field) { 1066 $row[] = $student->$field; 1067 } 1068 1069 $row[] = $attempts; 1070 1071 if ($data->lessonscored) { 1072 // Add the grade if the lesson is graded. 1073 $row[] = $bestgrade."%"; 1074 } 1075 1076 $table->data[] = $row; 1077 1078 // Add the student data. 1079 $dataforstudent->id = $student->id; 1080 $dataforstudent->fullname = $studentname; 1081 $dataforstudent->bestgrade = $bestgrade; 1082 $data->students[] = $dataforstudent; 1083 } 1084 } 1085 $students->close(); 1086 if ($data->numofattempts > 0) { 1087 $data->avescore = $data->avescore / $data->numofattempts; 1088 } 1089 1090 return array($table, $data); 1091 } 1092 1093 /** 1094 * Return information about one user attempt (including answers) 1095 * @param lesson $lesson lesson instance 1096 * @param int $userid the user id 1097 * @param int $attempt the attempt number 1098 * @return array the user answers (array) and user data stats (object) 1099 * @since Moodle 3.3 1100 */ 1101 function lesson_get_user_detailed_report_data(lesson $lesson, $userid, $attempt) { 1102 global $DB; 1103 1104 $context = $lesson->context; 1105 if (!empty($userid)) { 1106 // Apply overrides. 1107 $lesson->update_effective_access($userid); 1108 } 1109 1110 $pageid = 0; 1111 $lessonpages = $lesson->load_all_pages(); 1112 foreach ($lessonpages as $lessonpage) { 1113 if ($lessonpage->prevpageid == 0) { 1114 $pageid = $lessonpage->id; 1115 } 1116 } 1117 1118 // now gather the stats into an object 1119 $firstpageid = $pageid; 1120 $pagestats = array(); 1121 while ($pageid != 0) { // EOL 1122 $page = $lessonpages[$pageid]; 1123 $params = array ("lessonid" => $lesson->id, "pageid" => $page->id); 1124 if ($allanswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND pageid = :pageid", $params, "timeseen")) { 1125 // get them ready for processing 1126 $orderedanswers = array(); 1127 foreach ($allanswers as $singleanswer) { 1128 // ordering them like this, will help to find the single attempt record that we want to keep. 1129 $orderedanswers[$singleanswer->userid][$singleanswer->retry][] = $singleanswer; 1130 } 1131 // this is foreach user and for each try for that user, keep one attempt record 1132 foreach ($orderedanswers as $orderedanswer) { 1133 foreach($orderedanswer as $tries) { 1134 $page->stats($pagestats, $tries); 1135 } 1136 } 1137 } else { 1138 // no one answered yet... 1139 } 1140 //unset($orderedanswers); initialized above now 1141 $pageid = $page->nextpageid; 1142 } 1143 1144 $manager = lesson_page_type_manager::get($lesson); 1145 $qtypes = $manager->get_page_type_strings(); 1146 1147 $answerpages = array(); 1148 $answerpage = ""; 1149 $pageid = $firstpageid; 1150 // cycle through all the pages 1151 // foreach page, add to the $answerpages[] array all the data that is needed 1152 // from the question, the users attempt, and the statistics 1153 // grayout pages that the user did not answer and Branch, end of branch, cluster 1154 // and end of cluster pages 1155 while ($pageid != 0) { // EOL 1156 $page = $lessonpages[$pageid]; 1157 $answerpage = new stdClass; 1158 // Keep the original page object. 1159 $answerpage->page = $page; 1160 $data =''; 1161 1162 $answerdata = new stdClass; 1163 // Set some defaults for the answer data. 1164 $answerdata->score = null; 1165 $answerdata->response = null; 1166 $answerdata->responseformat = FORMAT_PLAIN; 1167 1168 $answerpage->title = format_string($page->title); 1169 1170 $options = new stdClass; 1171 $options->noclean = true; 1172 $options->overflowdiv = true; 1173 $options->context = $context; 1174 $answerpage->contents = format_text($page->contents, $page->contentsformat, $options); 1175 1176 $answerpage->qtype = $qtypes[$page->qtype].$page->option_description_string(); 1177 $answerpage->grayout = $page->grayout; 1178 $answerpage->context = $context; 1179 1180 if (empty($userid)) { 1181 // there is no userid, so set these vars and display stats. 1182 $answerpage->grayout = 0; 1183 $useranswer = null; 1184 } elseif ($useranswers = $DB->get_records("lesson_attempts",array("lessonid"=>$lesson->id, "userid"=>$userid, "retry"=>$attempt,"pageid"=>$page->id), "timeseen")) { 1185 // get the user's answer for this page 1186 // need to find the right one 1187 $i = 0; 1188 foreach ($useranswers as $userattempt) { 1189 $useranswer = $userattempt; 1190 $i++; 1191 if ($lesson->maxattempts == $i) { 1192 break; // reached maxattempts, break out 1193 } 1194 } 1195 } else { 1196 // user did not answer this page, gray it out and set some nulls 1197 $answerpage->grayout = 1; 1198 $useranswer = null; 1199 } 1200 $i = 0; 1201 $n = 0; 1202 $answerpages[] = $page->report_answers(clone($answerpage), clone($answerdata), $useranswer, $pagestats, $i, $n); 1203 $pageid = $page->nextpageid; 1204 } 1205 1206 $userstats = new stdClass; 1207 if (!empty($userid)) { 1208 $params = array("lessonid"=>$lesson->id, "userid"=>$userid); 1209 1210 $alreadycompleted = true; 1211 1212 if (!$grades = $DB->get_records_select("lesson_grades", "lessonid = :lessonid and userid = :userid", $params, "completed", "*", $attempt, 1)) { 1213 $userstats->grade = -1; 1214 $userstats->completed = -1; 1215 $alreadycompleted = false; 1216 } else { 1217 $userstats->grade = current($grades); 1218 $userstats->completed = $userstats->grade->completed; 1219 $userstats->grade = round($userstats->grade->grade, 2); 1220 } 1221 1222 if (!$times = $lesson->get_user_timers($userid, 'starttime', '*', $attempt, 1)) { 1223 $userstats->timetotake = -1; 1224 $alreadycompleted = false; 1225 } else { 1226 $userstats->timetotake = current($times); 1227 $userstats->timetotake = $userstats->timetotake->lessontime - $userstats->timetotake->starttime; 1228 } 1229 1230 if ($alreadycompleted) { 1231 $userstats->gradeinfo = lesson_grade($lesson, $attempt, $userid); 1232 } 1233 } 1234 1235 return array($answerpages, $userstats); 1236 } 1237 1238 /** 1239 * Return user's deadline for all lessons in a course, hereby taking into account group and user overrides. 1240 * 1241 * @param int $courseid the course id. 1242 * @return object An object with of all lessonsids and close unixdates in this course, 1243 * taking into account the most lenient overrides, if existing and 0 if no close date is set. 1244 */ 1245 function lesson_get_user_deadline($courseid) { 1246 global $DB, $USER; 1247 1248 // For teacher and manager/admins return lesson's deadline. 1249 if (has_capability('moodle/course:update', context_course::instance($courseid))) { 1250 $sql = "SELECT lesson.id, lesson.deadline AS userdeadline 1251 FROM {lesson} lesson 1252 WHERE lesson.course = :courseid"; 1253 1254 $results = $DB->get_records_sql($sql, array('courseid' => $courseid)); 1255 return $results; 1256 } 1257 1258 $sql = "SELECT a.id, 1259 COALESCE(v.userclose, v.groupclose, a.deadline, 0) AS userdeadline 1260 FROM ( 1261 SELECT lesson.id as lessonid, 1262 MAX(leo.deadline) AS userclose, MAX(qgo.deadline) AS groupclose 1263 FROM {lesson} lesson 1264 LEFT JOIN {lesson_overrides} leo on lesson.id = leo.lessonid AND leo.userid = :userid 1265 LEFT JOIN {groups_members} gm ON gm.userid = :useringroupid 1266 LEFT JOIN {lesson_overrides} qgo on lesson.id = qgo.lessonid AND qgo.groupid = gm.groupid 1267 WHERE lesson.course = :courseid 1268 GROUP BY lesson.id 1269 ) v 1270 JOIN {lesson} a ON a.id = v.lessonid"; 1271 1272 $results = $DB->get_records_sql($sql, array('userid' => $USER->id, 'useringroupid' => $USER->id, 'courseid' => $courseid)); 1273 return $results; 1274 1275 } 1276 1277 /** 1278 * Abstract class that page type's MUST inherit from. 1279 * 1280 * This is the abstract class that ALL add page type forms must extend. 1281 * You will notice that all but two of the methods this class contains are final. 1282 * Essentially the only thing that extending classes can do is extend custom_definition. 1283 * OR if it has a special requirement on creation it can extend construction_override 1284 * 1285 * @abstract 1286 * @copyright 2009 Sam Hemelryk 1287 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 1288 */ 1289 abstract class lesson_add_page_form_base extends moodleform { 1290 1291 /** 1292 * This is the classic define that is used to identify this pagetype. 1293 * Will be one of LESSON_* 1294 * @var int 1295 */ 1296 public $qtype; 1297 1298 /** 1299 * The simple string that describes the page type e.g. truefalse, multichoice 1300 * @var string 1301 */ 1302 public $qtypestring; 1303 1304 /** 1305 * An array of options used in the htmleditor 1306 * @var array 1307 */ 1308 protected $editoroptions = array(); 1309 1310 /** 1311 * True if this is a standard page of false if it does something special. 1312 * Questions are standard pages, branch tables are not 1313 * @var bool 1314 */ 1315 protected $standard = true; 1316 1317 /** 1318 * Answer format supported by question type. 1319 */ 1320 protected $answerformat = ''; 1321 1322 /** 1323 * Response format supported by question type. 1324 */ 1325 protected $responseformat = ''; 1326 1327 /** 1328 * Each page type can and should override this to add any custom elements to 1329 * the basic form that they want 1330 */ 1331 public function custom_definition() {} 1332 1333 /** 1334 * Returns answer format used by question type. 1335 */ 1336 public function get_answer_format() { 1337 return $this->answerformat; 1338 } 1339 1340 /** 1341 * Returns response format used by question type. 1342 */ 1343 public function get_response_format() { 1344 return $this->responseformat; 1345 } 1346 1347 /** 1348 * Used to determine if this is a standard page or a special page 1349 * @return bool 1350 */ 1351 public final function is_standard() { 1352 return (bool)$this->standard; 1353 } 1354 1355 /** 1356 * Add the required basic elements to the form. 1357 * 1358 * This method adds the basic elements to the form including title and contents 1359 * and then calls custom_definition(); 1360 */ 1361 public final function definition() { 1362 global $CFG; 1363 $mform = $this->_form; 1364 $editoroptions = $this->_customdata['editoroptions']; 1365 1366 if ($this->qtypestring != 'selectaqtype') { 1367 if ($this->_customdata['edit']) { 1368 $mform->addElement('header', 'qtypeheading', get_string('edit'. $this->qtypestring, 'lesson')); 1369 } else { 1370 $mform->addElement('header', 'qtypeheading', get_string('add'. $this->qtypestring, 'lesson')); 1371 } 1372 } 1373 1374 if (!empty($this->_customdata['returnto'])) { 1375 $mform->addElement('hidden', 'returnto', $this->_customdata['returnto']); 1376 $mform->setType('returnto', PARAM_LOCALURL); 1377 } 1378 1379 $mform->addElement('hidden', 'id'); 1380 $mform->setType('id', PARAM_INT); 1381 1382 $mform->addElement('hidden', 'pageid'); 1383 $mform->setType('pageid', PARAM_INT); 1384 1385 if ($this->standard === true) { 1386 $mform->addElement('hidden', 'qtype'); 1387 $mform->setType('qtype', PARAM_INT); 1388 1389 $mform->addElement('text', 'title', get_string('pagetitle', 'lesson'), array('size'=>70)); 1390 $mform->addRule('title', get_string('required'), 'required', null, 'client'); 1391 if (!empty($CFG->formatstringstriptags)) { 1392 $mform->setType('title', PARAM_TEXT); 1393 } else { 1394 $mform->setType('title', PARAM_CLEANHTML); 1395 } 1396 1397 $this->editoroptions = array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$this->_customdata['maxbytes']); 1398 $mform->addElement('editor', 'contents_editor', get_string('pagecontents', 'lesson'), null, $this->editoroptions); 1399 $mform->setType('contents_editor', PARAM_RAW); 1400 $mform->addRule('contents_editor', get_string('required'), 'required', null, 'client'); 1401 } 1402 1403 $this->custom_definition(); 1404 1405 if ($this->_customdata['edit'] === true) { 1406 $mform->addElement('hidden', 'edit', 1); 1407 $mform->setType('edit', PARAM_BOOL); 1408 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson')); 1409 } else if ($this->qtype === 'questiontype') { 1410 $this->add_action_buttons(get_string('cancel'), get_string('addaquestionpage', 'lesson')); 1411 } else { 1412 $this->add_action_buttons(get_string('cancel'), get_string('savepage', 'lesson')); 1413 } 1414 } 1415 1416 /** 1417 * Convenience function: Adds a jumpto select element 1418 * 1419 * @param string $name 1420 * @param string|null $label 1421 * @param int $selected The page to select by default 1422 */ 1423 protected final function add_jumpto($name, $label=null, $selected=LESSON_NEXTPAGE) { 1424 $title = get_string("jump", "lesson"); 1425 if ($label === null) { 1426 $label = $title; 1427 } 1428 if (is_int($name)) { 1429 $name = "jumpto[$name]"; 1430 } 1431 $this->_form->addElement('select', $name, $label, $this->_customdata['jumpto']); 1432 $this->_form->setDefault($name, $selected); 1433 $this->_form->addHelpButton($name, 'jumps', 'lesson'); 1434 } 1435 1436 /** 1437 * Convenience function: Adds a score input element 1438 * 1439 * @param string $name 1440 * @param string|null $label 1441 * @param mixed $value The default value 1442 */ 1443 protected final function add_score($name, $label=null, $value=null) { 1444 if ($label === null) { 1445 $label = get_string("score", "lesson"); 1446 } 1447 1448 if (is_int($name)) { 1449 $name = "score[$name]"; 1450 } 1451 $this->_form->addElement('text', $name, $label, array('size'=>5)); 1452 $this->_form->setType($name, PARAM_INT); 1453 if ($value !== null) { 1454 $this->_form->setDefault($name, $value); 1455 } 1456 $this->_form->addHelpButton($name, 'score', 'lesson'); 1457 1458 // Score is only used for custom scoring. Disable the element when not in use to stop some confusion. 1459 if (!$this->_customdata['lesson']->custom) { 1460 $this->_form->freeze($name); 1461 } 1462 } 1463 1464 /** 1465 * Convenience function: Adds an answer editor 1466 * 1467 * @param int $count The count of the element to add 1468 * @param string $label, null means default 1469 * @param bool $required 1470 * @param string $format 1471 * @param array $help Add help text via the addHelpButton. Must be an array which contains the string identifier and 1472 * component as it's elements 1473 * @return void 1474 */ 1475 protected final function add_answer($count, $label = null, $required = false, $format= '', array $help = []) { 1476 if ($label === null) { 1477 $label = get_string('answer', 'lesson'); 1478 } 1479 1480 if ($format == LESSON_ANSWER_HTML) { 1481 $this->_form->addElement('editor', 'answer_editor['.$count.']', $label, 1482 array('rows' => '4', 'columns' => '80'), 1483 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes'])); 1484 $this->_form->setType('answer_editor['.$count.']', PARAM_RAW); 1485 $this->_form->setDefault('answer_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML)); 1486 } else { 1487 $this->_form->addElement('text', 'answer_editor['.$count.']', $label, 1488 array('size' => '50', 'maxlength' => '200')); 1489 $this->_form->setType('answer_editor['.$count.']', PARAM_TEXT); 1490 } 1491 1492 if ($required) { 1493 $this->_form->addRule('answer_editor['.$count.']', get_string('required'), 'required', null, 'client'); 1494 } 1495 1496 if ($help) { 1497 $this->_form->addHelpButton("answer_editor[$count]", $help['identifier'], $help['component']); 1498 } 1499 } 1500 /** 1501 * Convenience function: Adds an response editor 1502 * 1503 * @param int $count The count of the element to add 1504 * @param string $label, null means default 1505 * @param bool $required 1506 * @return void 1507 */ 1508 protected final function add_response($count, $label = null, $required = false) { 1509 if ($label === null) { 1510 $label = get_string('response', 'lesson'); 1511 } 1512 $this->_form->addElement('editor', 'response_editor['.$count.']', $label, 1513 array('rows' => '4', 'columns' => '80'), 1514 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $this->_customdata['maxbytes'])); 1515 $this->_form->setType('response_editor['.$count.']', PARAM_RAW); 1516 $this->_form->setDefault('response_editor['.$count.']', array('text' => '', 'format' => FORMAT_HTML)); 1517 1518 if ($required) { 1519 $this->_form->addRule('response_editor['.$count.']', get_string('required'), 'required', null, 'client'); 1520 } 1521 } 1522 1523 /** 1524 * A function that gets called upon init of this object by the calling script. 1525 * 1526 * This can be used to process an immediate action if required. Currently it 1527 * is only used in special cases by non-standard page types. 1528 * 1529 * @return bool 1530 */ 1531 public function construction_override($pageid, lesson $lesson) { 1532 return true; 1533 } 1534 } 1535 1536 1537 1538 /** 1539 * Class representation of a lesson 1540 * 1541 * This class is used the interact with, and manage a lesson once instantiated. 1542 * If you need to fetch a lesson object you can do so by calling 1543 * 1544 * <code> 1545 * lesson::load($lessonid); 1546 * // or 1547 * $lessonrecord = $DB->get_record('lesson', $lessonid); 1548 * $lesson = new lesson($lessonrecord); 1549 * </code> 1550 * 1551 * The class itself extends lesson_base as all classes within the lesson module should 1552 * 1553 * These properties are from the database 1554 * @property int $id The id of this lesson 1555 * @property int $course The ID of the course this lesson belongs to 1556 * @property string $name The name of this lesson 1557 * @property int $practice Flag to toggle this as a practice lesson 1558 * @property int $modattempts Toggle to allow the user to go back and review answers 1559 * @property int $usepassword Toggle the use of a password for entry 1560 * @property string $password The password to require users to enter 1561 * @property int $dependency ID of another lesson this lesson is dependent on 1562 * @property string $conditions Conditions of the lesson dependency 1563 * @property int $grade The maximum grade a user can achieve (%) 1564 * @property int $custom Toggle custom scoring on or off 1565 * @property int $ongoing Toggle display of an ongoing score 1566 * @property int $usemaxgrade How retakes are handled (max=1, mean=0) 1567 * @property int $maxanswers The max number of answers or branches 1568 * @property int $maxattempts The maximum number of attempts a user can record 1569 * @property int $review Toggle use or wrong answer review button 1570 * @property int $nextpagedefault Override the default next page 1571 * @property int $feedback Toggles display of default feedback 1572 * @property int $minquestions Sets a minimum value of pages seen when calculating grades 1573 * @property int $maxpages Maximum number of pages this lesson can contain 1574 * @property int $retake Flag to allow users to retake a lesson 1575 * @property int $activitylink Relate this lesson to another lesson 1576 * @property string $mediafile File to pop up to or webpage to display 1577 * @property int $mediaheight Sets the height of the media file popup 1578 * @property int $mediawidth Sets the width of the media file popup 1579 * @property int $mediaclose Toggle display of a media close button 1580 * @property int $slideshow Flag for whether branch pages should be shown as slideshows 1581 * @property int $width Width of slideshow 1582 * @property int $height Height of slideshow 1583 * @property string $bgcolor Background colour of slideshow 1584 * @property int $displayleft Display a left menu 1585 * @property int $displayleftif Sets the condition on which the left menu is displayed 1586 * @property int $progressbar Flag to toggle display of a lesson progress bar 1587 * @property int $available Timestamp of when this lesson becomes available 1588 * @property int $deadline Timestamp of when this lesson is no longer available 1589 * @property int $timemodified Timestamp when lesson was last modified 1590 * @property int $allowofflineattempts Whether to allow the lesson to be attempted offline in the mobile app 1591 * 1592 * These properties are calculated 1593 * @property int $firstpageid Id of the first page of this lesson (prevpageid=0) 1594 * @property int $lastpageid Id of the last page of this lesson (nextpageid=0) 1595 * 1596 * @copyright 2009 Sam Hemelryk 1597 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 1598 */ 1599 class lesson extends lesson_base { 1600 1601 /** 1602 * The id of the first page (where prevpageid = 0) gets set and retrieved by 1603 * {@see get_firstpageid()} by directly calling <code>$lesson->firstpageid;</code> 1604 * @var int 1605 */ 1606 protected $firstpageid = null; 1607 /** 1608 * The id of the last page (where nextpageid = 0) gets set and retrieved by 1609 * {@see get_lastpageid()} by directly calling <code>$lesson->lastpageid;</code> 1610 * @var int 1611 */ 1612 protected $lastpageid = null; 1613 /** 1614 * An array used to cache the pages associated with this lesson after the first 1615 * time they have been loaded. 1616 * A note to developers: If you are going to be working with MORE than one or 1617 * two pages from a lesson you should probably call {@see $lesson->load_all_pages()} 1618 * in order to save excess database queries. 1619 * @var array An array of lesson_page objects 1620 */ 1621 protected $pages = array(); 1622 /** 1623 * Flag that gets set to true once all of the pages associated with the lesson 1624 * have been loaded. 1625 * @var bool 1626 */ 1627 protected $loadedallpages = false; 1628 1629 /** 1630 * Course module object gets set and retrieved by directly calling <code>$lesson->cm;</code> 1631 * @see get_cm() 1632 * @var stdClass 1633 */ 1634 protected $cm = null; 1635 1636 /** 1637 * Course object gets set and retrieved by directly calling <code>$lesson->courserecord;</code> 1638 * @see get_courserecord() 1639 * @var stdClass 1640 */ 1641 protected $courserecord = null; 1642 1643 /** 1644 * Context object gets set and retrieved by directly calling <code>$lesson->context;</code> 1645 * @see get_context() 1646 * @var stdClass 1647 */ 1648 protected $context = null; 1649 1650 /** 1651 * Constructor method 1652 * 1653 * @param object $properties 1654 * @param stdClass $cm course module object 1655 * @param stdClass $course course object 1656 * @since Moodle 3.3 1657 */ 1658 public function __construct($properties, $cm = null, $course = null) { 1659 parent::__construct($properties); 1660 $this->cm = $cm; 1661 $this->courserecord = $course; 1662 } 1663 1664 /** 1665 * Simply generates a lesson object given an array/object of properties 1666 * Overrides {@see lesson_base->create()} 1667 * @static 1668 * @param object|array $properties 1669 * @return lesson 1670 */ 1671 public static function create($properties) { 1672 return new lesson($properties); 1673 } 1674 1675 /** 1676 * Generates a lesson object from the database given its id 1677 * @static 1678 * @param int $lessonid 1679 * @return lesson 1680 */ 1681 public static function load($lessonid) { 1682 global $DB; 1683 1684 if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) { 1685 throw new \moodle_exception('invalidcoursemodule'); 1686 } 1687 return new lesson($lesson); 1688 } 1689 1690 /** 1691 * Deletes this lesson from the database 1692 */ 1693 public function delete() { 1694 global $CFG, $DB; 1695 require_once($CFG->libdir.'/gradelib.php'); 1696 require_once($CFG->dirroot.'/calendar/lib.php'); 1697 1698 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course); 1699 $context = context_module::instance($cm->id); 1700 1701 $this->delete_all_overrides(); 1702 1703 grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1)); 1704 1705 // We must delete the module record after we delete the grade item. 1706 $DB->delete_records("lesson", array("id"=>$this->properties->id)); 1707 $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id)); 1708 $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id)); 1709 $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id)); 1710 $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id)); 1711 $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id)); 1712 $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id)); 1713 if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) { 1714 $coursecontext = context_course::instance($cm->course); 1715 foreach($events as $event) { 1716 $event->context = $coursecontext; 1717 $event = calendar_event::load($event); 1718 $event->delete(); 1719 } 1720 } 1721 1722 // Delete files associated with this module. 1723 $fs = get_file_storage(); 1724 $fs->delete_area_files($context->id); 1725 1726 return true; 1727 } 1728 1729 /** 1730 * Deletes a lesson override from the database and clears any corresponding calendar events 1731 * 1732 * @param int $overrideid The id of the override being deleted 1733 * @return bool true on success 1734 */ 1735 public function delete_override($overrideid) { 1736 global $CFG, $DB; 1737 1738 require_once($CFG->dirroot . '/calendar/lib.php'); 1739 1740 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course); 1741 1742 $override = $DB->get_record('lesson_overrides', array('id' => $overrideid), '*', MUST_EXIST); 1743 1744 // Delete the events. 1745 $conds = array('modulename' => 'lesson', 1746 'instance' => $this->properties->id); 1747 if (isset($override->userid)) { 1748 $conds['userid'] = $override->userid; 1749 $cachekey = "{$cm->instance}_u_{$override->userid}"; 1750 } else { 1751 $conds['groupid'] = $override->groupid; 1752 $cachekey = "{$cm->instance}_g_{$override->groupid}"; 1753 } 1754 $events = $DB->get_records('event', $conds); 1755 foreach ($events as $event) { 1756 $eventold = calendar_event::load($event); 1757 $eventold->delete(); 1758 } 1759 1760 $DB->delete_records('lesson_overrides', array('id' => $overrideid)); 1761 cache::make('mod_lesson', 'overrides')->delete($cachekey); 1762 1763 // Set the common parameters for one of the events we will be triggering. 1764 $params = array( 1765 'objectid' => $override->id, 1766 'context' => context_module::instance($cm->id), 1767 'other' => array( 1768 'lessonid' => $override->lessonid 1769 ) 1770 ); 1771 // Determine which override deleted event to fire. 1772 if (!empty($override->userid)) { 1773 $params['relateduserid'] = $override->userid; 1774 $event = \mod_lesson\event\user_override_deleted::create($params); 1775 } else { 1776 $params['other']['groupid'] = $override->groupid; 1777 $event = \mod_lesson\event\group_override_deleted::create($params); 1778 } 1779 1780 // Trigger the override deleted event. 1781 $event->add_record_snapshot('lesson_overrides', $override); 1782 $event->trigger(); 1783 1784 return true; 1785 } 1786 1787 /** 1788 * Deletes all lesson overrides from the database and clears any corresponding calendar events 1789 */ 1790 public function delete_all_overrides() { 1791 global $DB; 1792 1793 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $this->properties->id), 'id'); 1794 foreach ($overrides as $override) { 1795 $this->delete_override($override->id); 1796 } 1797 } 1798 1799 /** 1800 * Checks user enrollment in the current course. 1801 * 1802 * @param int $userid 1803 * @return null|stdClass user record 1804 */ 1805 public function is_participant($userid) { 1806 return is_enrolled($this->get_context(), $userid, 'mod/lesson:view', $this->show_only_active_users()); 1807 } 1808 1809 /** 1810 * Check is only active users in course should be shown. 1811 * 1812 * @return bool true if only active users should be shown. 1813 */ 1814 public function show_only_active_users() { 1815 return !has_capability('moodle/course:viewsuspendedusers', $this->get_context()); 1816 } 1817 1818 /** 1819 * Updates the lesson properties with override information for a user. 1820 * 1821 * Algorithm: For each lesson setting, if there is a matching user-specific override, 1822 * then use that otherwise, if there are group-specific overrides, return the most 1823 * lenient combination of them. If neither applies, leave the quiz setting unchanged. 1824 * 1825 * Special case: if there is more than one password that applies to the user, then 1826 * lesson->extrapasswords will contain an array of strings giving the remaining 1827 * passwords. 1828 * 1829 * @param int $userid The userid. 1830 */ 1831 public function update_effective_access($userid) { 1832 global $DB; 1833 1834 // Check for user override. 1835 $override = $DB->get_record('lesson_overrides', array('lessonid' => $this->properties->id, 'userid' => $userid)); 1836 1837 if (!$override) { 1838 $override = new stdClass(); 1839 $override->available = null; 1840 $override->deadline = null; 1841 $override->timelimit = null; 1842 $override->review = null; 1843 $override->maxattempts = null; 1844 $override->retake = null; 1845 $override->password = null; 1846 } 1847 1848 // Check for group overrides. 1849 $groupings = groups_get_user_groups($this->properties->course, $userid); 1850 1851 if (!empty($groupings[0])) { 1852 // Select all overrides that apply to the User's groups. 1853 list($extra, $params) = $DB->get_in_or_equal(array_values($groupings[0])); 1854 $sql = "SELECT * FROM {lesson_overrides} 1855 WHERE groupid $extra AND lessonid = ?"; 1856 $params[] = $this->properties->id; 1857 $records = $DB->get_records_sql($sql, $params); 1858 1859 // Combine the overrides. 1860 $availables = array(); 1861 $deadlines = array(); 1862 $timelimits = array(); 1863 $reviews = array(); 1864 $attempts = array(); 1865 $retakes = array(); 1866 $passwords = array(); 1867 1868 foreach ($records as $gpoverride) { 1869 if (isset($gpoverride->available)) { 1870 $availables[] = $gpoverride->available; 1871 } 1872 if (isset($gpoverride->deadline)) { 1873 $deadlines[] = $gpoverride->deadline; 1874 } 1875 if (isset($gpoverride->timelimit)) { 1876 $timelimits[] = $gpoverride->timelimit; 1877 } 1878 if (isset($gpoverride->review)) { 1879 $reviews[] = $gpoverride->review; 1880 } 1881 if (isset($gpoverride->maxattempts)) { 1882 $attempts[] = $gpoverride->maxattempts; 1883 } 1884 if (isset($gpoverride->retake)) { 1885 $retakes[] = $gpoverride->retake; 1886 } 1887 if (isset($gpoverride->password)) { 1888 $passwords[] = $gpoverride->password; 1889 } 1890 } 1891 // If there is a user override for a setting, ignore the group override. 1892 if (is_null($override->available) && count($availables)) { 1893 $override->available = min($availables); 1894 } 1895 if (is_null($override->deadline) && count($deadlines)) { 1896 if (in_array(0, $deadlines)) { 1897 $override->deadline = 0; 1898 } else { 1899 $override->deadline = max($deadlines); 1900 } 1901 } 1902 if (is_null($override->timelimit) && count($timelimits)) { 1903 if (in_array(0, $timelimits)) { 1904 $override->timelimit = 0; 1905 } else { 1906 $override->timelimit = max($timelimits); 1907 } 1908 } 1909 if (is_null($override->review) && count($reviews)) { 1910 $override->review = max($reviews); 1911 } 1912 if (is_null($override->maxattempts) && count($attempts)) { 1913 $override->maxattempts = max($attempts); 1914 } 1915 if (is_null($override->retake) && count($retakes)) { 1916 $override->retake = max($retakes); 1917 } 1918 if (is_null($override->password) && count($passwords)) { 1919 $override->password = array_shift($passwords); 1920 if (count($passwords)) { 1921 $override->extrapasswords = $passwords; 1922 } 1923 } 1924 1925 } 1926 1927 // Merge with lesson defaults. 1928 $keys = array('available', 'deadline', 'timelimit', 'maxattempts', 'review', 'retake'); 1929 foreach ($keys as $key) { 1930 if (isset($override->{$key})) { 1931 $this->properties->{$key} = $override->{$key}; 1932 } 1933 } 1934 1935 // Special handling of lesson usepassword and password. 1936 if (isset($override->password)) { 1937 if ($override->password == '') { 1938 $this->properties->usepassword = 0; 1939 } else { 1940 $this->properties->usepassword = 1; 1941 $this->properties->password = $override->password; 1942 if (isset($override->extrapasswords)) { 1943 $this->properties->extrapasswords = $override->extrapasswords; 1944 } 1945 } 1946 } 1947 } 1948 1949 /** 1950 * Fetches messages from the session that may have been set in previous page 1951 * actions. 1952 * 1953 * <code> 1954 * // Do not call this method directly instead use 1955 * $lesson->messages; 1956 * </code> 1957 * 1958 * @return array 1959 */ 1960 protected function get_messages() { 1961 global $SESSION; 1962 1963 $messages = array(); 1964 if (!empty($SESSION->lesson_messages) && is_array($SESSION->lesson_messages) && array_key_exists($this->properties->id, $SESSION->lesson_messages)) { 1965 $messages = $SESSION->lesson_messages[$this->properties->id]; 1966 unset($SESSION->lesson_messages[$this->properties->id]); 1967 } 1968 1969 return $messages; 1970 } 1971 1972 /** 1973 * Get all of the attempts for the current user. 1974 * 1975 * @param int $retries 1976 * @param bool $correct Optional: only fetch correct attempts 1977 * @param int $pageid Optional: only fetch attempts at the given page 1978 * @param int $userid Optional: defaults to the current user if not set 1979 * @return array|false 1980 */ 1981 public function get_attempts($retries, $correct=false, $pageid=null, $userid=null) { 1982 global $USER, $DB; 1983 $params = array("lessonid"=>$this->properties->id, "userid"=>$userid, "retry"=>$retries); 1984 if ($correct) { 1985 $params['correct'] = 1; 1986 } 1987 if ($pageid !== null) { 1988 $params['pageid'] = $pageid; 1989 } 1990 if ($userid === null) { 1991 $params['userid'] = $USER->id; 1992 } 1993 return $DB->get_records('lesson_attempts', $params, 'timeseen ASC'); 1994 } 1995 1996 1997 /** 1998 * Get a list of content pages (formerly known as branch tables) viewed in the lesson for the given user during an attempt. 1999 * 2000 * @param int $lessonattempt the lesson attempt number (also known as retries) 2001 * @param int $userid the user id to retrieve the data from 2002 * @param string $sort an order to sort the results in (a valid SQL ORDER BY parameter) 2003 * @param string $fields a comma separated list of fields to return 2004 * @return array of pages 2005 * @since Moodle 3.3 2006 */ 2007 public function get_content_pages_viewed($lessonattempt, $userid = null, $sort = '', $fields = '*') { 2008 global $USER, $DB; 2009 2010 if ($userid === null) { 2011 $userid = $USER->id; 2012 } 2013 $conditions = array("lessonid" => $this->properties->id, "userid" => $userid, "retry" => $lessonattempt); 2014 return $DB->get_records('lesson_branch', $conditions, $sort, $fields); 2015 } 2016 2017 /** 2018 * Returns the first page for the lesson or false if there isn't one. 2019 * 2020 * This method should be called via the magic method __get(); 2021 * <code> 2022 * $firstpage = $lesson->firstpage; 2023 * </code> 2024 * 2025 * @return lesson_page|bool Returns the lesson_page specialised object or false 2026 */ 2027 protected function get_firstpage() { 2028 $pages = $this->load_all_pages(); 2029 if (count($pages) > 0) { 2030 foreach ($pages as $page) { 2031 if ((int)$page->prevpageid === 0) { 2032 return $page; 2033 } 2034 } 2035 } 2036 return false; 2037 } 2038 2039 /** 2040 * Returns the last page for the lesson or false if there isn't one. 2041 * 2042 * This method should be called via the magic method __get(); 2043 * <code> 2044 * $lastpage = $lesson->lastpage; 2045 * </code> 2046 * 2047 * @return lesson_page|bool Returns the lesson_page specialised object or false 2048 */ 2049 protected function get_lastpage() { 2050 $pages = $this->load_all_pages(); 2051 if (count($pages) > 0) { 2052 foreach ($pages as $page) { 2053 if ((int)$page->nextpageid === 0) { 2054 return $page; 2055 } 2056 } 2057 } 2058 return false; 2059 } 2060 2061 /** 2062 * Returns the id of the first page of this lesson. (prevpageid = 0) 2063 * @return int 2064 */ 2065 protected function get_firstpageid() { 2066 global $DB; 2067 if ($this->firstpageid == null) { 2068 if (!$this->loadedallpages) { 2069 $firstpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'prevpageid'=>0)); 2070 if (!$firstpageid) { 2071 throw new \moodle_exception('cannotfindfirstpage', 'lesson'); 2072 } 2073 $this->firstpageid = $firstpageid; 2074 } else { 2075 $firstpage = $this->get_firstpage(); 2076 $this->firstpageid = $firstpage->id; 2077 } 2078 } 2079 return $this->firstpageid; 2080 } 2081 2082 /** 2083 * Returns the id of the last page of this lesson. (nextpageid = 0) 2084 * @return int 2085 */ 2086 public function get_lastpageid() { 2087 global $DB; 2088 if ($this->lastpageid == null) { 2089 if (!$this->loadedallpages) { 2090 $lastpageid = $DB->get_field('lesson_pages', 'id', array('lessonid'=>$this->properties->id, 'nextpageid'=>0)); 2091 if (!$lastpageid) { 2092 throw new \moodle_exception('cannotfindlastpage', 'lesson'); 2093 } 2094 $this->lastpageid = $lastpageid; 2095 } else { 2096 $lastpageid = $this->get_lastpage(); 2097 $this->lastpageid = $lastpageid->id; 2098 } 2099 } 2100 2101 return $this->lastpageid; 2102 } 2103 2104 /** 2105 * Gets the next page id to display after the one that is provided. 2106 * @param int $nextpageid 2107 * @return bool 2108 */ 2109 public function get_next_page($nextpageid) { 2110 global $USER, $DB; 2111 $allpages = $this->load_all_pages(); 2112 if ($this->properties->nextpagedefault) { 2113 // in Flash Card mode...first get number of retakes 2114 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id)); 2115 shuffle($allpages); 2116 $found = false; 2117 if ($this->properties->nextpagedefault == LESSON_UNSEENPAGE) { 2118 foreach ($allpages as $nextpage) { 2119 if (!$DB->count_records("lesson_attempts", array("pageid" => $nextpage->id, "userid" => $USER->id, "retry" => $nretakes))) { 2120 $found = true; 2121 break; 2122 } 2123 } 2124 } elseif ($this->properties->nextpagedefault == LESSON_UNANSWEREDPAGE) { 2125 foreach ($allpages as $nextpage) { 2126 if (!$DB->count_records("lesson_attempts", array('pageid' => $nextpage->id, 'userid' => $USER->id, 'correct' => 1, 'retry' => $nretakes))) { 2127 $found = true; 2128 break; 2129 } 2130 } 2131 } 2132 if ($found) { 2133 if ($this->properties->maxpages) { 2134 // check number of pages viewed (in the lesson) 2135 if ($DB->count_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes)) >= $this->properties->maxpages) { 2136 return LESSON_EOL; 2137 } 2138 } 2139 return $nextpage->id; 2140 } 2141 } 2142 // In a normal lesson mode 2143 foreach ($allpages as $nextpage) { 2144 if ((int)$nextpage->id === (int)$nextpageid) { 2145 return $nextpage->id; 2146 } 2147 } 2148 return LESSON_EOL; 2149 } 2150 2151 /** 2152 * Sets a message against the session for this lesson that will displayed next 2153 * time the lesson processes messages 2154 * 2155 * @param string $message 2156 * @param string $class 2157 * @param string $align 2158 * @return bool 2159 */ 2160 public function add_message($message, $class="notifyproblem", $align='center') { 2161 global $SESSION; 2162 2163 if (empty($SESSION->lesson_messages) || !is_array($SESSION->lesson_messages)) { 2164 $SESSION->lesson_messages = array(); 2165 $SESSION->lesson_messages[$this->properties->id] = array(); 2166 } else if (!array_key_exists($this->properties->id, $SESSION->lesson_messages)) { 2167 $SESSION->lesson_messages[$this->properties->id] = array(); 2168 } 2169 2170 $SESSION->lesson_messages[$this->properties->id][] = array($message, $class, $align); 2171 2172 return true; 2173 } 2174 2175 /** 2176 * Check if the lesson is accessible at the present time 2177 * @return bool True if the lesson is accessible, false otherwise 2178 */ 2179 public function is_accessible() { 2180 $available = $this->properties->available; 2181 $deadline = $this->properties->deadline; 2182 return (($available == 0 || time() >= $available) && ($deadline == 0 || time() < $deadline)); 2183 } 2184 2185 /** 2186 * Starts the lesson time for the current user 2187 * @return bool Returns true 2188 */ 2189 public function start_timer() { 2190 global $USER, $DB; 2191 2192 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course, 2193 false, MUST_EXIST); 2194 2195 // Trigger lesson started event. 2196 $event = \mod_lesson\event\lesson_started::create(array( 2197 'objectid' => $this->properties()->id, 2198 'context' => context_module::instance($cm->id), 2199 'courseid' => $this->properties()->course 2200 )); 2201 $event->trigger(); 2202 2203 $USER->startlesson[$this->properties->id] = true; 2204 2205 $timenow = time(); 2206 $startlesson = new stdClass; 2207 $startlesson->lessonid = $this->properties->id; 2208 $startlesson->userid = $USER->id; 2209 $startlesson->starttime = $timenow; 2210 $startlesson->lessontime = $timenow; 2211 if (WS_SERVER) { 2212 $startlesson->timemodifiedoffline = $timenow; 2213 } 2214 $DB->insert_record('lesson_timer', $startlesson); 2215 if ($this->properties->timelimit) { 2216 $this->add_message(get_string('timelimitwarning', 'lesson', format_time($this->properties->timelimit)), 'center'); 2217 } 2218 return true; 2219 } 2220 2221 /** 2222 * Updates the timer to the current time and returns the new timer object 2223 * @param bool $restart If set to true the timer is restarted 2224 * @param bool $continue If set to true AND $restart=true then the timer 2225 * will continue from a previous attempt 2226 * @return stdClass The new timer 2227 */ 2228 public function update_timer($restart=false, $continue=false, $endreached =false) { 2229 global $USER, $DB; 2230 2231 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course); 2232 2233 // clock code 2234 // get time information for this user 2235 if (!$timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1)) { 2236 $this->start_timer(); 2237 $timer = $this->get_user_timers($USER->id, 'starttime DESC', '*', 0, 1); 2238 } 2239 $timer = current($timer); // This will get the latest start time record. 2240 2241 if ($restart) { 2242 if ($continue) { 2243 // continue a previous test, need to update the clock (think this option is disabled atm) 2244 $timer->starttime = time() - ($timer->lessontime - $timer->starttime); 2245 2246 // Trigger lesson resumed event. 2247 $event = \mod_lesson\event\lesson_resumed::create(array( 2248 'objectid' => $this->properties->id, 2249 'context' => context_module::instance($cm->id), 2250 'courseid' => $this->properties->course 2251 )); 2252 $event->trigger(); 2253 2254 } else { 2255 // starting over, so reset the clock 2256 $timer->starttime = time(); 2257 2258 // Trigger lesson restarted event. 2259 $event = \mod_lesson\event\lesson_restarted::create(array( 2260 'objectid' => $this->properties->id, 2261 'context' => context_module::instance($cm->id), 2262 'courseid' => $this->properties->course 2263 )); 2264 $event->trigger(); 2265 2266 } 2267 } 2268 2269 $timenow = time(); 2270 $timer->lessontime = $timenow; 2271 if (WS_SERVER) { 2272 $timer->timemodifiedoffline = $timenow; 2273 } 2274 $timer->completed = $endreached; 2275 $DB->update_record('lesson_timer', $timer); 2276 2277 // Update completion state. 2278 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course, 2279 false, MUST_EXIST); 2280 $course = get_course($cm->course); 2281 $completion = new completion_info($course); 2282 if ($completion->is_enabled($cm) && $this->properties()->completiontimespent > 0) { 2283 $completion->update_state($cm, COMPLETION_COMPLETE); 2284 } 2285 return $timer; 2286 } 2287 2288 /** 2289 * Updates the timer to the current time then stops it by unsetting the user var 2290 * @return bool Returns true 2291 */ 2292 public function stop_timer() { 2293 global $USER, $DB; 2294 unset($USER->startlesson[$this->properties->id]); 2295 2296 $cm = get_coursemodule_from_instance('lesson', $this->properties()->id, $this->properties()->course, 2297 false, MUST_EXIST); 2298 2299 // Trigger lesson ended event. 2300 $event = \mod_lesson\event\lesson_ended::create(array( 2301 'objectid' => $this->properties()->id, 2302 'context' => context_module::instance($cm->id), 2303 'courseid' => $this->properties()->course 2304 )); 2305 $event->trigger(); 2306 2307 return $this->update_timer(false, false, true); 2308 } 2309 2310 /** 2311 * Checks to see if the lesson has pages 2312 */ 2313 public function has_pages() { 2314 global $DB; 2315 $pagecount = $DB->count_records('lesson_pages', array('lessonid'=>$this->properties->id)); 2316 return ($pagecount>0); 2317 } 2318 2319 /** 2320 * Returns the link for the related activity 2321 * @return string 2322 */ 2323 public function link_for_activitylink() { 2324 global $DB; 2325 $module = $DB->get_record('course_modules', array('id' => $this->properties->activitylink)); 2326 if ($module) { 2327 $modname = $DB->get_field('modules', 'name', array('id' => $module->module)); 2328 if ($modname) { 2329 $instancename = $DB->get_field($modname, 'name', array('id' => $module->instance)); 2330 if ($instancename) { 2331 return html_writer::link(new moodle_url('/mod/'.$modname.'/view.php', 2332 array('id' => $this->properties->activitylink)), get_string('activitylinkname', 2333 'lesson', $instancename), array('class' => 'centerpadded lessonbutton standardbutton pr-3')); 2334 } 2335 } 2336 } 2337 return ''; 2338 } 2339 2340 /** 2341 * Loads the requested page. 2342 * 2343 * This function will return the requested page id as either a specialised 2344 * lesson_page object OR as a generic lesson_page. 2345 * If the page has been loaded previously it will be returned from the pages 2346 * array, otherwise it will be loaded from the database first 2347 * 2348 * @param int $pageid 2349 * @return lesson_page A lesson_page object or an object that extends it 2350 */ 2351 public function load_page($pageid) { 2352 if (!array_key_exists($pageid, $this->pages)) { 2353 $manager = lesson_page_type_manager::get($this); 2354 $this->pages[$pageid] = $manager->load_page($pageid, $this); 2355 } 2356 return $this->pages[$pageid]; 2357 } 2358 2359 /** 2360 * Loads ALL of the pages for this lesson 2361 * 2362 * @return array An array containing all pages from this lesson 2363 */ 2364 public function load_all_pages() { 2365 if (!$this->loadedallpages) { 2366 $manager = lesson_page_type_manager::get($this); 2367 $this->pages = $manager->load_all_pages($this); 2368 $this->loadedallpages = true; 2369 } 2370 return $this->pages; 2371 } 2372 2373 /** 2374 * Duplicate the lesson page. 2375 * 2376 * @param int $pageid Page ID of the page to duplicate. 2377 * @return void. 2378 */ 2379 public function duplicate_page($pageid) { 2380 global $PAGE; 2381 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course); 2382 $context = context_module::instance($cm->id); 2383 // Load the page. 2384 $page = $this->load_page($pageid); 2385 $properties = $page->properties(); 2386 // The create method checks to see if these properties are set and if not sets them to zero, hence the unsetting here. 2387 if (!$properties->qoption) { 2388 unset($properties->qoption); 2389 } 2390 if (!$properties->layout) { 2391 unset($properties->layout); 2392 } 2393 if (!$properties->display) { 2394 unset($properties->display); 2395 } 2396 2397 $properties->pageid = $pageid; 2398 // Add text and format into the format required to create a new page. 2399 $properties->contents_editor = array( 2400 'text' => $properties->contents, 2401 'format' => $properties->contentsformat 2402 ); 2403 $answers = $page->get_answers(); 2404 // Answers need to be added to $properties. 2405 $i = 0; 2406 $answerids = array(); 2407 foreach ($answers as $answer) { 2408 // Needs to be rearranged to work with the create function. 2409 $properties->answer_editor[$i] = array( 2410 'text' => $answer->answer, 2411 'format' => $answer->answerformat 2412 ); 2413 2414 $properties->response_editor[$i] = array( 2415 'text' => $answer->response, 2416 'format' => $answer->responseformat 2417 ); 2418 $answerids[] = $answer->id; 2419 2420 $properties->jumpto[$i] = $answer->jumpto; 2421 $properties->score[$i] = $answer->score; 2422 2423 $i++; 2424 } 2425 // Create the duplicate page. 2426 $newlessonpage = lesson_page::create($properties, $this, $context, $PAGE->course->maxbytes); 2427 $newanswers = $newlessonpage->get_answers(); 2428 // Copy over the file areas as well. 2429 $this->copy_page_files('page_contents', $pageid, $newlessonpage->id, $context->id); 2430 $j = 0; 2431 foreach ($newanswers as $answer) { 2432 if (isset($answer->answer) && strpos($answer->answer, '@@PLUGINFILE@@') !== false) { 2433 $this->copy_page_files('page_answers', $answerids[$j], $answer->id, $context->id); 2434 } 2435 if (isset($answer->response) && !is_array($answer->response) && strpos($answer->response, '@@PLUGINFILE@@') !== false) { 2436 $this->copy_page_files('page_responses', $answerids[$j], $answer->id, $context->id); 2437 } 2438 $j++; 2439 } 2440 } 2441 2442 /** 2443 * Copy the files from one page to another. 2444 * 2445 * @param string $filearea Area that the files are stored. 2446 * @param int $itemid Item ID. 2447 * @param int $newitemid The item ID for the new page. 2448 * @param int $contextid Context ID for this page. 2449 * @return void. 2450 */ 2451 protected function copy_page_files($filearea, $itemid, $newitemid, $contextid) { 2452 $fs = get_file_storage(); 2453 $files = $fs->get_area_files($contextid, 'mod_lesson', $filearea, $itemid); 2454 foreach ($files as $file) { 2455 $fieldupdates = array('itemid' => $newitemid); 2456 $fs->create_file_from_storedfile($fieldupdates, $file); 2457 } 2458 } 2459 2460 /** 2461 * Determines if a jumpto value is correct or not. 2462 * 2463 * returns true if jumpto page is (logically) after the pageid page or 2464 * if the jumpto value is a special value. Returns false in all other cases. 2465 * 2466 * @param int $pageid Id of the page from which you are jumping from. 2467 * @param int $jumpto The jumpto number. 2468 * @return boolean True or false after a series of tests. 2469 **/ 2470 public function jumpto_is_correct($pageid, $jumpto) { 2471 global $DB; 2472 2473 // first test the special values 2474 if (!$jumpto) { 2475 // same page 2476 return false; 2477 } elseif ($jumpto == LESSON_NEXTPAGE) { 2478 return true; 2479 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) { 2480 return true; 2481 } elseif ($jumpto == LESSON_RANDOMPAGE) { 2482 return true; 2483 } elseif ($jumpto == LESSON_CLUSTERJUMP) { 2484 return true; 2485 } elseif ($jumpto == LESSON_EOL) { 2486 return true; 2487 } 2488 2489 $pages = $this->load_all_pages(); 2490 $apageid = $pages[$pageid]->nextpageid; 2491 while ($apageid != 0) { 2492 if ($jumpto == $apageid) { 2493 return true; 2494 } 2495 $apageid = $pages[$apageid]->nextpageid; 2496 } 2497 return false; 2498 } 2499 2500 /** 2501 * Returns the time a user has remaining on this lesson 2502 * @param int $starttime Starttime timestamp 2503 * @return string 2504 */ 2505 public function time_remaining($starttime) { 2506 $timeleft = $starttime + $this->properties->timelimit - time(); 2507 $hours = floor($timeleft/3600); 2508 $timeleft = $timeleft - ($hours * 3600); 2509 $minutes = floor($timeleft/60); 2510 $secs = $timeleft - ($minutes * 60); 2511 2512 if ($minutes < 10) { 2513 $minutes = "0$minutes"; 2514 } 2515 if ($secs < 10) { 2516 $secs = "0$secs"; 2517 } 2518 $output = array(); 2519 $output[] = $hours; 2520 $output[] = $minutes; 2521 $output[] = $secs; 2522 $output = implode(':', $output); 2523 return $output; 2524 } 2525 2526 /** 2527 * Interprets LESSON_CLUSTERJUMP jumpto value. 2528 * 2529 * This will select a page randomly 2530 * and the page selected will be inbetween a cluster page and end of clutter or end of lesson 2531 * and the page selected will be a page that has not been viewed already 2532 * and if any pages are within a branch table or end of branch then only 1 page within 2533 * the branch table or end of branch will be randomly selected (sub clustering). 2534 * 2535 * @param int $pageid Id of the current page from which we are jumping from. 2536 * @param int $userid Id of the user. 2537 * @return int The id of the next page. 2538 **/ 2539 public function cluster_jump($pageid, $userid=null) { 2540 global $DB, $USER; 2541 2542 if ($userid===null) { 2543 $userid = $USER->id; 2544 } 2545 // get the number of retakes 2546 if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->properties->id, "userid"=>$userid))) { 2547 $retakes = 0; 2548 } 2549 // get all the lesson_attempts aka what the user has seen 2550 $seenpages = array(); 2551 if ($attempts = $this->get_attempts($retakes)) { 2552 foreach ($attempts as $attempt) { 2553 $seenpages[$attempt->pageid] = $attempt->pageid; 2554 } 2555 2556 } 2557 2558 // get the lesson pages 2559 $lessonpages = $this->load_all_pages(); 2560 // find the start of the cluster 2561 while ($pageid != 0) { // this condition should not be satisfied... should be a cluster page 2562 if ($lessonpages[$pageid]->qtype == LESSON_PAGE_CLUSTER) { 2563 break; 2564 } 2565 $pageid = $lessonpages[$pageid]->prevpageid; 2566 } 2567 2568 $clusterpages = array(); 2569 $clusterpages = $this->get_sub_pages_of($pageid, array(LESSON_PAGE_ENDOFCLUSTER)); 2570 $unseen = array(); 2571 foreach ($clusterpages as $key=>$cluster) { 2572 // Remove the page if it is in a branch table or is an endofbranch. 2573 if ($this->is_sub_page_of_type($cluster->id, 2574 array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER)) 2575 || $cluster->qtype == LESSON_PAGE_ENDOFBRANCH) { 2576 unset($clusterpages[$key]); 2577 } else if ($cluster->qtype == LESSON_PAGE_BRANCHTABLE) { 2578 // If branchtable, check to see if any pages inside have been viewed. 2579 $branchpages = $this->get_sub_pages_of($cluster->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH)); 2580 $flag = true; 2581 foreach ($branchpages as $branchpage) { 2582 if (array_key_exists($branchpage->id, $seenpages)) { // Check if any of the pages have been viewed. 2583 $flag = false; 2584 } 2585 } 2586 if ($flag && count($branchpages) > 0) { 2587 // Add branch table. 2588 $unseen[] = $cluster; 2589 } 2590 } elseif ($cluster->is_unseen($seenpages)) { 2591 $unseen[] = $cluster; 2592 } 2593 } 2594 2595 if (count($unseen) > 0) { 2596 // it does not contain elements, then use exitjump, otherwise find out next page/branch 2597 $nextpage = $unseen[rand(0, count($unseen)-1)]; 2598 if ($nextpage->qtype == LESSON_PAGE_BRANCHTABLE) { 2599 // if branch table, then pick a random page inside of it 2600 $branchpages = $this->get_sub_pages_of($nextpage->id, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH)); 2601 return $branchpages[rand(0, count($branchpages)-1)]->id; 2602 } else { // otherwise, return the page's id 2603 return $nextpage->id; 2604 } 2605 } else { 2606 // seen all there is to see, leave the cluster 2607 if (end($clusterpages)->nextpageid == 0) { 2608 return LESSON_EOL; 2609 } else { 2610 $clusterendid = $pageid; 2611 while ($clusterendid != 0) { // This condition should not be satisfied... should be an end of cluster page. 2612 if ($lessonpages[$clusterendid]->qtype == LESSON_PAGE_ENDOFCLUSTER) { 2613 break; 2614 } 2615 $clusterendid = $lessonpages[$clusterendid]->nextpageid; 2616 } 2617 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $clusterendid, "lessonid" => $this->properties->id)); 2618 if ($exitjump == LESSON_NEXTPAGE) { 2619 $exitjump = $lessonpages[$clusterendid]->nextpageid; 2620 } 2621 if ($exitjump == 0) { 2622 return LESSON_EOL; 2623 } else if (in_array($exitjump, array(LESSON_EOL, LESSON_PREVIOUSPAGE))) { 2624 return $exitjump; 2625 } else { 2626 if (!array_key_exists($exitjump, $lessonpages)) { 2627 $found = false; 2628 foreach ($lessonpages as $page) { 2629 if ($page->id === $clusterendid) { 2630 $found = true; 2631 } else if ($page->qtype == LESSON_PAGE_ENDOFCLUSTER) { 2632 $exitjump = $DB->get_field("lesson_answers", "jumpto", array("pageid" => $page->id, "lessonid" => $this->properties->id)); 2633 if ($exitjump == LESSON_NEXTPAGE) { 2634 $exitjump = $lessonpages[$page->id]->nextpageid; 2635 } 2636 break; 2637 } 2638 } 2639 } 2640 if (!array_key_exists($exitjump, $lessonpages)) { 2641 return LESSON_EOL; 2642 } 2643 // Check to see that the return type is not a cluster. 2644 if ($lessonpages[$exitjump]->qtype == LESSON_PAGE_CLUSTER) { 2645 // If the exitjump is a cluster then go through this function again and try to find an unseen question. 2646 $exitjump = $this->cluster_jump($exitjump, $userid); 2647 } 2648 return $exitjump; 2649 } 2650 } 2651 } 2652 } 2653 2654 /** 2655 * Finds all pages that appear to be a subtype of the provided pageid until 2656 * an end point specified within $ends is encountered or no more pages exist 2657 * 2658 * @param int $pageid 2659 * @param array $ends An array of LESSON_PAGE_* types that signify an end of 2660 * the subtype 2661 * @return array An array of specialised lesson_page objects 2662 */ 2663 public function get_sub_pages_of($pageid, array $ends) { 2664 $lessonpages = $this->load_all_pages(); 2665 $pageid = $lessonpages[$pageid]->nextpageid; // move to the first page after the branch table 2666 $pages = array(); 2667 2668 while (true) { 2669 if ($pageid == 0 || in_array($lessonpages[$pageid]->qtype, $ends)) { 2670 break; 2671 } 2672 $pages[] = $lessonpages[$pageid]; 2673 $pageid = $lessonpages[$pageid]->nextpageid; 2674 } 2675 2676 return $pages; 2677 } 2678 2679 /** 2680 * Checks to see if the specified page[id] is a subpage of a type specified in 2681 * the $types array, until either there are no more pages of we find a type 2682 * corresponding to that of a type specified in $ends 2683 * 2684 * @param int $pageid The id of the page to check 2685 * @param array $types An array of types that would signify this page was a subpage 2686 * @param array $ends An array of types that mean this is not a subpage 2687 * @return bool 2688 */ 2689 public function is_sub_page_of_type($pageid, array $types, array $ends) { 2690 $pages = $this->load_all_pages(); 2691 $pageid = $pages[$pageid]->prevpageid; // move up one 2692 2693 array_unshift($ends, 0); 2694 // go up the pages till branch table 2695 while (true) { 2696 if ($pageid==0 || in_array($pages[$pageid]->qtype, $ends)) { 2697 return false; 2698 } else if (in_array($pages[$pageid]->qtype, $types)) { 2699 return true; 2700 } 2701 $pageid = $pages[$pageid]->prevpageid; 2702 } 2703 } 2704 2705 /** 2706 * Move a page resorting all other pages. 2707 * 2708 * @param int $pageid 2709 * @param int $after 2710 * @return void 2711 */ 2712 public function resort_pages($pageid, $after) { 2713 global $CFG; 2714 2715 $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course); 2716 $context = context_module::instance($cm->id); 2717 2718 $pages = $this->load_all_pages(); 2719 2720 if (!array_key_exists($pageid, $pages) || ($after!=0 && !array_key_exists($after, $pages))) { 2721 throw new \moodle_exception('cannotfindpages', 'lesson', "$CFG->wwwroot/mod/lesson/edit.php?id=$cm->id"); 2722 } 2723 2724 $pagetomove = clone($pages[$pageid]); 2725 unset($pages[$pageid]); 2726 2727 $pageids = array(); 2728 if ($after === 0) { 2729 $pageids['p0'] = $pageid; 2730 } 2731 foreach ($pages as $page) { 2732 $pageids[] = $page->id; 2733 if ($page->id == $after) { 2734 $pageids[] = $pageid; 2735 } 2736 } 2737 2738 $pageidsref = $pageids; 2739 reset($pageidsref); 2740 $prev = 0; 2741 $next = next($pageidsref); 2742 foreach ($pageids as $pid) { 2743 if ($pid === $pageid) { 2744 $page = $pagetomove; 2745 } else { 2746 $page = $pages[$pid]; 2747 } 2748 if ($page->prevpageid != $prev || $page->nextpageid != $next) { 2749 $page->move($next, $prev); 2750 2751 if ($pid === $pageid) { 2752 // We will trigger an event. 2753 $pageupdated = array('next' => $next, 'prev' => $prev); 2754 } 2755 } 2756 2757 $prev = $page->id; 2758 $next = next($pageidsref); 2759 if (!$next) { 2760 $next = 0; 2761 } 2762 } 2763 2764 // Trigger an event: page moved. 2765 if (!empty($pageupdated)) { 2766 $eventparams = array( 2767 'context' => $context, 2768 'objectid' => $pageid, 2769 'other' => array( 2770 'pagetype' => $page->get_typestring(), 2771 'prevpageid' => $pageupdated['prev'], 2772 'nextpageid' => $pageupdated['next'] 2773 ) 2774 ); 2775 $event = \mod_lesson\event\page_moved::create($eventparams); 2776 $event->trigger(); 2777 } 2778 2779 } 2780 2781 /** 2782 * Return the lesson context object. 2783 * 2784 * @return stdClass context 2785 * @since Moodle 3.3 2786 */ 2787 public function get_context() { 2788 if ($this->context == null) { 2789 $this->context = context_module::instance($this->get_cm()->id); 2790 } 2791 return $this->context; 2792 } 2793 2794 /** 2795 * Set the lesson course module object. 2796 * 2797 * @param stdClass $cm course module objct 2798 * @since Moodle 3.3 2799 */ 2800 private function set_cm($cm) { 2801 $this->cm = $cm; 2802 } 2803 2804 /** 2805 * Return the lesson course module object. 2806 * 2807 * @return stdClass course module 2808 * @since Moodle 3.3 2809 */ 2810 public function get_cm() { 2811 if ($this->cm == null) { 2812 $this->cm = get_coursemodule_from_instance('lesson', $this->properties->id); 2813 } 2814 return $this->cm; 2815 } 2816 2817 /** 2818 * Set the lesson course object. 2819 * 2820 * @param stdClass $course course objct 2821 * @since Moodle 3.3 2822 */ 2823 private function set_courserecord($course) { 2824 $this->courserecord = $course; 2825 } 2826 2827 /** 2828 * Return the lesson course object. 2829 * 2830 * @return stdClass course 2831 * @since Moodle 3.3 2832 */ 2833 public function get_courserecord() { 2834 global $DB; 2835 2836 if ($this->courserecord == null) { 2837 $this->courserecord = $DB->get_record('course', array('id' => $this->properties->course)); 2838 } 2839 return $this->courserecord; 2840 } 2841 2842 /** 2843 * Check if the user can manage the lesson activity. 2844 * 2845 * @return bool true if the user can manage the lesson 2846 * @since Moodle 3.3 2847 */ 2848 public function can_manage() { 2849 return has_capability('mod/lesson:manage', $this->get_context()); 2850 } 2851 2852 /** 2853 * Check if time restriction is applied. 2854 * 2855 * @return mixed false if there aren't restrictions or an object with the restriction information 2856 * @since Moodle 3.3 2857 */ 2858 public function get_time_restriction_status() { 2859 if ($this->can_manage()) { 2860 return false; 2861 } 2862 2863 if (!$this->is_accessible()) { 2864 if ($this->properties->deadline != 0 && time() > $this->properties->deadline) { 2865 $status = ['reason' => 'lessonclosed', 'time' => $this->properties->deadline]; 2866 } else { 2867 $status = ['reason' => 'lessonopen', 'time' => $this->properties->available]; 2868 } 2869 return (object) $status; 2870 } 2871 return false; 2872 } 2873 2874 /** 2875 * Check if password restriction is applied. 2876 * 2877 * @param string $userpassword the user password to check (if the restriction is set) 2878 * @return mixed false if there aren't restrictions or an object with the restriction information 2879 * @since Moodle 3.3 2880 */ 2881 public function get_password_restriction_status($userpassword) { 2882 global $USER; 2883 if ($this->can_manage()) { 2884 return false; 2885 } 2886 2887 if ($this->properties->usepassword && empty($USER->lessonloggedin[$this->id])) { 2888 $correctpass = false; 2889 if (!empty($userpassword) && 2890 (($this->properties->password == md5(trim($userpassword))) || ($this->properties->password == trim($userpassword)))) { 2891 // With or without md5 for backward compatibility (MDL-11090). 2892 $correctpass = true; 2893 $USER->lessonloggedin[$this->id] = true; 2894 } else if (isset($this->properties->extrapasswords)) { 2895 // Group overrides may have additional passwords. 2896 foreach ($this->properties->extrapasswords as $password) { 2897 if (strcmp($password, md5(trim($userpassword))) === 0 || strcmp($password, trim($userpassword)) === 0) { 2898 $correctpass = true; 2899 $USER->lessonloggedin[$this->id] = true; 2900 } 2901 } 2902 } 2903 return !$correctpass; 2904 } 2905 return false; 2906 } 2907 2908 /** 2909 * Check if dependencies restrictions are applied. 2910 * 2911 * @return mixed false if there aren't restrictions or an object with the restriction information 2912 * @since Moodle 3.3 2913 */ 2914 public function get_dependencies_restriction_status() { 2915 global $DB, $USER; 2916 if ($this->can_manage()) { 2917 return false; 2918 } 2919 2920 if ($dependentlesson = $DB->get_record('lesson', array('id' => $this->properties->dependency))) { 2921 // Lesson exists, so we can proceed. 2922 $conditions = unserialize_object($this->properties->conditions); 2923 // Assume false for all. 2924 $errors = array(); 2925 // Check for the timespent condition. 2926 if (!empty($conditions->timespent)) { 2927 $timespent = false; 2928 if ($attempttimes = $DB->get_records('lesson_timer', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) { 2929 // Go through all the times and test to see if any of them satisfy the condition. 2930 foreach ($attempttimes as $attempttime) { 2931 $duration = $attempttime->lessontime - $attempttime->starttime; 2932 if ($conditions->timespent < $duration / 60) { 2933 $timespent = true; 2934 } 2935 } 2936 } 2937 if (!$timespent) { 2938 $errors[] = get_string('timespenterror', 'lesson', $conditions->timespent); 2939 } 2940 } 2941 // Check for the gradebetterthan condition. 2942 if (!empty($conditions->gradebetterthan)) { 2943 $gradebetterthan = false; 2944 if ($studentgrades = $DB->get_records('lesson_grades', array("userid" => $USER->id, "lessonid" => $dependentlesson->id))) { 2945 // Go through all the grades and test to see if any of them satisfy the condition. 2946 foreach ($studentgrades as $studentgrade) { 2947 if ($studentgrade->grade >= $conditions->gradebetterthan) { 2948 $gradebetterthan = true; 2949 } 2950 } 2951 } 2952 if (!$gradebetterthan) { 2953 $errors[] = get_string('gradebetterthanerror', 'lesson', $conditions->gradebetterthan); 2954 } 2955 } 2956 // Check for the completed condition. 2957 if (!empty($conditions->completed)) { 2958 if (!$DB->count_records('lesson_grades', array('userid' => $USER->id, 'lessonid' => $dependentlesson->id))) { 2959 $errors[] = get_string('completederror', 'lesson'); 2960 } 2961 } 2962 if (!empty($errors)) { 2963 return (object) ['errors' => $errors, 'dependentlesson' => $dependentlesson]; 2964 } 2965 } 2966 return false; 2967 } 2968 2969 /** 2970 * Check if the lesson is in review mode. (The user already finished it and retakes are not allowed). 2971 * 2972 * @return bool true if is in review mode 2973 * @since Moodle 3.3 2974 */ 2975 public function is_in_review_mode() { 2976 global $DB, $USER; 2977 2978 $userhasgrade = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id)); 2979 if ($userhasgrade && !$this->properties->retake) { 2980 return true; 2981 } 2982 return false; 2983 } 2984 2985 /** 2986 * Return the last page the current user saw. 2987 * 2988 * @param int $retriescount the number of retries for the lesson (the last retry number). 2989 * @return mixed false if the user didn't see the lesson or the last page id 2990 */ 2991 public function get_last_page_seen($retriescount) { 2992 global $DB, $USER; 2993 2994 $lastpageseen = false; 2995 $allattempts = $this->get_attempts($retriescount); 2996 if (!empty($allattempts)) { 2997 $attempt = end($allattempts); 2998 $attemptpage = $this->load_page($attempt->pageid); 2999 $jumpto = $DB->get_field('lesson_answers', 'jumpto', array('id' => $attempt->answerid)); 3000 // Convert the jumpto to a proper page id. 3001 if ($jumpto == 0) { 3002 // Check if a question has been incorrectly answered AND no more attempts at it are left. 3003 $nattempts = $this->get_attempts($attempt->retry, false, $attempt->pageid, $USER->id); 3004 if (count($nattempts) >= $this->properties->maxattempts) { 3005 $lastpageseen = $this->get_next_page($attemptpage->nextpageid); 3006 } else { 3007 $lastpageseen = $attempt->pageid; 3008 } 3009 } else if ($jumpto == LESSON_NEXTPAGE) { 3010 $lastpageseen = $this->get_next_page($attemptpage->nextpageid); 3011 } else if ($jumpto == LESSON_CLUSTERJUMP) { 3012 $lastpageseen = $this->cluster_jump($attempt->pageid); 3013 } else { 3014 $lastpageseen = $jumpto; 3015 } 3016 } 3017 3018 if ($branchtables = $this->get_content_pages_viewed($retriescount, $USER->id, 'timeseen DESC')) { 3019 // In here, user has viewed a branch table. 3020 $lastbranchtable = current($branchtables); 3021 if (count($allattempts) > 0) { 3022 if ($lastbranchtable->timeseen > $attempt->timeseen) { 3023 // This branch table was viewed more recently than the question page. 3024 if (!empty($lastbranchtable->nextpageid)) { 3025 $lastpageseen = $lastbranchtable->nextpageid; 3026 } else { 3027 // Next page ID did not exist prior to MDL-34006. 3028 $lastpageseen = $lastbranchtable->pageid; 3029 } 3030 } 3031 } else { 3032 // Has not answered any questions but has viewed a branch table. 3033 if (!empty($lastbranchtable->nextpageid)) { 3034 $lastpageseen = $lastbranchtable->nextpageid; 3035 } else { 3036 // Next page ID did not exist prior to MDL-34006. 3037 $lastpageseen = $lastbranchtable->pageid; 3038 } 3039 } 3040 } 3041 return $lastpageseen; 3042 } 3043 3044 /** 3045 * Return the number of retries in a lesson for a given user. 3046 * 3047 * @param int $userid the user id 3048 * @return int the retries count 3049 * @since Moodle 3.3 3050 */ 3051 public function count_user_retries($userid) { 3052 global $DB; 3053 3054 return $DB->count_records('lesson_grades', array("lessonid" => $this->properties->id, "userid" => $userid)); 3055 } 3056 3057 /** 3058 * Check if a user left a timed session. 3059 * 3060 * @param int $retriescount the number of retries for the lesson (the last retry number). 3061 * @return true if the user left the timed session 3062 * @since Moodle 3.3 3063 */ 3064 public function left_during_timed_session($retriescount) { 3065 global $DB, $USER; 3066 3067 $conditions = array('lessonid' => $this->properties->id, 'userid' => $USER->id, 'retry' => $retriescount); 3068 return $DB->count_records('lesson_attempts', $conditions) > 0 || $DB->count_records('lesson_branch', $conditions) > 0; 3069 } 3070 3071 /** 3072 * Trigger module viewed event and set the module viewed for completion. 3073 * 3074 * @since Moodle 3.3 3075 */ 3076 public function set_module_viewed() { 3077 global $CFG; 3078 require_once($CFG->libdir . '/completionlib.php'); 3079 3080 // Trigger module viewed event. 3081 $event = \mod_lesson\event\course_module_viewed::create(array( 3082 'objectid' => $this->properties->id, 3083 'context' => $this->get_context() 3084 )); 3085 $event->add_record_snapshot('course_modules', $this->get_cm()); 3086 $event->add_record_snapshot('course', $this->get_courserecord()); 3087 $event->trigger(); 3088 3089 // Mark as viewed. 3090 $completion = new completion_info($this->get_courserecord()); 3091 $completion->set_module_viewed($this->get_cm()); 3092 } 3093 3094 /** 3095 * Return the timers in the current lesson for the given user. 3096 * 3097 * @param int $userid the user id 3098 * @param string $sort an order to sort the results in (optional, a valid SQL ORDER BY parameter). 3099 * @param string $fields a comma separated list of fields to return 3100 * @param int $limitfrom return a subset of records, starting at this point (optional). 3101 * @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set). 3102 * @return array list of timers for the given user in the lesson 3103 * @since Moodle 3.3 3104 */ 3105 public function get_user_timers($userid = null, $sort = '', $fields = '*', $limitfrom = 0, $limitnum = 0) { 3106 global $DB, $USER; 3107 3108 if ($userid === null) { 3109 $userid = $USER->id; 3110 } 3111 3112 $params = array('lessonid' => $this->properties->id, 'userid' => $userid); 3113 return $DB->get_records('lesson_timer', $params, $sort, $fields, $limitfrom, $limitnum); 3114 } 3115 3116 /** 3117 * Check if the user is out of time in a timed lesson. 3118 * 3119 * @param stdClass $timer timer object 3120 * @return bool True if the user is on time, false is the user ran out of time 3121 * @since Moodle 3.3 3122 */ 3123 public function check_time($timer) { 3124 if ($this->properties->timelimit) { 3125 $timeleft = $timer->starttime + $this->properties->timelimit - time(); 3126 if ($timeleft <= 0) { 3127 // Out of time. 3128 $this->add_message(get_string('eolstudentoutoftime', 'lesson')); 3129 return false; 3130 } else if ($timeleft < 60) { 3131 // One minute warning. 3132 $this->add_message(get_string('studentoneminwarning', 'lesson')); 3133 } 3134 } 3135 return true; 3136 } 3137 3138 /** 3139 * Add different informative messages to the given page. 3140 * 3141 * @param lesson_page $page page object 3142 * @param reviewmode $bool whether we are in review mode or not 3143 * @since Moodle 3.3 3144 */ 3145 public function add_messages_on_page_view(lesson_page $page, $reviewmode) { 3146 global $DB, $USER; 3147 3148 if (!$this->can_manage()) { 3149 if ($page->qtype == LESSON_PAGE_BRANCHTABLE && $this->properties->minquestions) { 3150 // Tell student how many questions they have seen, how many are required and their grade. 3151 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id)); 3152 $gradeinfo = lesson_grade($this, $ntries); 3153 if ($gradeinfo->attempts) { 3154 if ($gradeinfo->nquestions < $this->properties->minquestions) { 3155 $a = new stdClass; 3156 $a->nquestions = $gradeinfo->nquestions; 3157 $a->minquestions = $this->properties->minquestions; 3158 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a)); 3159 } 3160 3161 if (!$reviewmode && $this->properties->ongoing) { 3162 $this->add_message(get_string("numberofcorrectanswers", "lesson", $gradeinfo->earned), 'notify'); 3163 if ($this->properties->grade != GRADE_TYPE_NONE) { 3164 $a = new stdClass; 3165 $a->grade = format_float($gradeinfo->grade * $this->properties->grade / 100, 1); 3166 $a->total = $this->properties->grade; 3167 $this->add_message(get_string('yourcurrentgradeisoutof', 'lesson', $a), 'notify'); 3168 } 3169 } 3170 } 3171 } 3172 } else { 3173 if ($this->properties->timelimit) { 3174 $this->add_message(get_string('teachertimerwarning', 'lesson')); 3175 } 3176 if (lesson_display_teacher_warning($this)) { 3177 // This is the warning msg for teachers to inform them that cluster 3178 // and unseen does not work while logged in as a teacher. 3179 $warningvars = new stdClass(); 3180 $warningvars->cluster = get_string('clusterjump', 'lesson'); 3181 $warningvars->unseen = get_string('unseenpageinbranch', 'lesson'); 3182 $this->add_message(get_string('teacherjumpwarning', 'lesson', $warningvars)); 3183 } 3184 } 3185 } 3186 3187 /** 3188 * Get the ongoing score message for the user (depending on the user permission and lesson settings). 3189 * 3190 * @return str the ongoing score message 3191 * @since Moodle 3.3 3192 */ 3193 public function get_ongoing_score_message() { 3194 global $USER, $DB; 3195 3196 $context = $this->get_context(); 3197 3198 if (has_capability('mod/lesson:manage', $context)) { 3199 return get_string('teacherongoingwarning', 'lesson'); 3200 } else { 3201 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id)); 3202 if (isset($USER->modattempts[$this->properties->id])) { 3203 $ntries--; 3204 } 3205 $gradeinfo = lesson_grade($this, $ntries); 3206 $a = new stdClass; 3207 if ($this->properties->custom) { 3208 $a->score = $gradeinfo->earned; 3209 $a->currenthigh = $gradeinfo->total; 3210 return get_string("ongoingcustom", "lesson", $a); 3211 } else { 3212 $a->correct = $gradeinfo->earned; 3213 $a->viewed = $gradeinfo->attempts; 3214 return get_string("ongoingnormal", "lesson", $a); 3215 } 3216 } 3217 } 3218 3219 /** 3220 * Calculate the progress of the current user in the lesson. 3221 * 3222 * @return int the progress (scale 0-100) 3223 * @since Moodle 3.3 3224 */ 3225 public function calculate_progress() { 3226 global $USER, $DB; 3227 3228 // Check if the user is reviewing the attempt. 3229 if (isset($USER->modattempts[$this->properties->id])) { 3230 return 100; 3231 } 3232 3233 // All of the lesson pages. 3234 $pages = $this->load_all_pages(); 3235 foreach ($pages as $page) { 3236 if ($page->prevpageid == 0) { 3237 $pageid = $page->id; // Find the first page id. 3238 break; 3239 } 3240 } 3241 3242 // Current attempt number. 3243 if (!$ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id))) { 3244 $ntries = 0; // May not be necessary. 3245 } 3246 3247 $viewedpageids = array(); 3248 if ($attempts = $this->get_attempts($ntries, false)) { 3249 foreach ($attempts as $attempt) { 3250 $viewedpageids[$attempt->pageid] = $attempt; 3251 } 3252 } 3253 3254 $viewedbranches = array(); 3255 // Collect all of the branch tables viewed. 3256 if ($branches = $this->get_content_pages_viewed($ntries, $USER->id, 'timeseen ASC', 'id, pageid')) { 3257 foreach ($branches as $branch) { 3258 $viewedbranches[$branch->pageid] = $branch; 3259 } 3260 $viewedpageids = array_merge($viewedpageids, $viewedbranches); 3261 } 3262 3263 // Filter out the following pages: 3264 // - End of Cluster 3265 // - End of Branch 3266 // - Pages found inside of Clusters 3267 // Do not filter out Cluster Page(s) because we count a cluster as one. 3268 // By keeping the cluster page, we get our 1. 3269 $validpages = array(); 3270 while ($pageid != 0) { 3271 $pageid = $pages[$pageid]->valid_page_and_view($validpages, $viewedpageids); 3272 } 3273 3274 // Progress calculation as a percent. 3275 $progress = round(count($viewedpageids) / count($validpages), 2) * 100; 3276 return (int) $progress; 3277 } 3278 3279 /** 3280 * Calculate the correct page and prepare contents for a given page id (could be a page jump id). 3281 * 3282 * @param int $pageid the given page id 3283 * @param mod_lesson_renderer $lessonoutput the lesson output rendered 3284 * @param bool $reviewmode whether we are in review mode or not 3285 * @param bool $redirect Optional, default to true. Set to false to avoid redirection and return the page to redirect. 3286 * @return array the page object and contents 3287 * @throws moodle_exception 3288 * @since Moodle 3.3 3289 */ 3290 public function prepare_page_and_contents($pageid, $lessonoutput, $reviewmode, $redirect = true) { 3291 global $USER, $CFG; 3292 3293 $page = $this->load_page($pageid); 3294 // Check if the page is of a special type and if so take any nessecary action. 3295 $newpageid = $page->callback_on_view($this->can_manage(), $redirect); 3296 3297 // Avoid redirections returning the jump to special page id. 3298 if (!$redirect && is_numeric($newpageid) && $newpageid < 0) { 3299 return array($newpageid, null, null); 3300 } 3301 3302 if (is_numeric($newpageid)) { 3303 $page = $this->load_page($newpageid); 3304 } 3305 3306 // Add different informative messages to the given page. 3307 $this->add_messages_on_page_view($page, $reviewmode); 3308 3309 if (is_array($page->answers) && count($page->answers) > 0) { 3310 // This is for modattempts option. Find the users previous answer to this page, 3311 // and then display it below in answer processing. 3312 if (isset($USER->modattempts[$this->properties->id])) { 3313 $retries = $this->count_user_retries($USER->id); 3314 if (!$attempts = $this->get_attempts($retries - 1, false, $page->id)) { 3315 throw new moodle_exception('cannotfindpreattempt', 'lesson'); 3316 } 3317 $attempt = end($attempts); 3318 $USER->modattempts[$this->properties->id] = $attempt; 3319 } else { 3320 $attempt = false; 3321 } 3322 $lessoncontent = $lessonoutput->display_page($this, $page, $attempt); 3323 } else { 3324 require_once($CFG->dirroot . '/mod/lesson/view_form.php'); 3325 $data = new stdClass; 3326 $data->id = $this->get_cm()->id; 3327 $data->pageid = $page->id; 3328 $data->newpageid = $this->get_next_page($page->nextpageid); 3329 3330 $customdata = array( 3331 'title' => $page->title, 3332 'contents' => $page->get_contents() 3333 ); 3334 $mform = new lesson_page_without_answers($CFG->wwwroot.'/mod/lesson/continue.php', $customdata); 3335 $mform->set_data($data); 3336 ob_start(); 3337 $mform->display(); 3338 $lessoncontent = ob_get_contents(); 3339 ob_end_clean(); 3340 } 3341 3342 return array($page->id, $page, $lessoncontent); 3343 } 3344 3345 /** 3346 * This returns a real page id to jump to (or LESSON_EOL) after processing page responses. 3347 * 3348 * @param lesson_page $page lesson page 3349 * @param int $newpageid the new page id 3350 * @return int the real page to jump to (or end of lesson) 3351 * @since Moodle 3.3 3352 */ 3353 public function calculate_new_page_on_jump(lesson_page $page, $newpageid) { 3354 global $USER, $DB; 3355 3356 $canmanage = $this->can_manage(); 3357 3358 if (isset($USER->modattempts[$this->properties->id])) { 3359 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time. 3360 if ($USER->modattempts[$this->properties->id]->pageid == $page->id && $page->nextpageid == 0) { 3361 // Remember, this session variable holds the pageid of the last page that the user saw. 3362 $newpageid = LESSON_EOL; 3363 } else { 3364 $nretakes = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id)); 3365 $nretakes--; // Make sure we are looking at the right try. 3366 $attempts = $DB->get_records("lesson_attempts", array("lessonid" => $this->properties->id, "userid" => $USER->id, "retry" => $nretakes), "timeseen", "id, pageid"); 3367 $found = false; 3368 $temppageid = 0; 3369 // Make sure that the newpageid always defaults to something valid. 3370 $newpageid = LESSON_EOL; 3371 foreach ($attempts as $attempt) { 3372 if ($found && $temppageid != $attempt->pageid) { 3373 // Now try to find the next page, make sure next few attempts do no belong to current page. 3374 $newpageid = $attempt->pageid; 3375 break; 3376 } 3377 if ($attempt->pageid == $page->id) { 3378 $found = true; // If found current page. 3379 $temppageid = $attempt->pageid; 3380 } 3381 } 3382 } 3383 } else if ($newpageid != LESSON_CLUSTERJUMP && $page->id != 0 && $newpageid > 0) { 3384 // Going to check to see if the page that the user is going to view next, is a cluster page. 3385 // If so, dont display, go into the cluster. 3386 // The $newpageid > 0 is used to filter out all of the negative code jumps. 3387 $newpage = $this->load_page($newpageid); 3388 if ($overridenewpageid = $newpage->override_next_page($newpageid)) { 3389 $newpageid = $overridenewpageid; 3390 } 3391 } else if ($newpageid == LESSON_UNSEENBRANCHPAGE) { 3392 if ($canmanage) { 3393 if ($page->nextpageid == 0) { 3394 $newpageid = LESSON_EOL; 3395 } else { 3396 $newpageid = $page->nextpageid; 3397 } 3398 } else { 3399 $newpageid = lesson_unseen_question_jump($this, $USER->id, $page->id); 3400 } 3401 } else if ($newpageid == LESSON_PREVIOUSPAGE) { 3402 $newpageid = $page->prevpageid; 3403 } else if ($newpageid == LESSON_RANDOMPAGE) { 3404 $newpageid = lesson_random_question_jump($this, $page->id); 3405 } else if ($newpageid == LESSON_CLUSTERJUMP) { 3406 if ($canmanage) { 3407 if ($page->nextpageid == 0) { // If teacher, go to next page. 3408 $newpageid = LESSON_EOL; 3409 } else { 3410 $newpageid = $page->nextpageid; 3411 } 3412 } else { 3413 $newpageid = $this->cluster_jump($page->id); 3414 } 3415 } else if ($newpageid == 0) { 3416 $newpageid = $page->id; 3417 } else if ($newpageid == LESSON_NEXTPAGE) { 3418 $newpageid = $this->get_next_page($page->nextpageid); 3419 } 3420 3421 return $newpageid; 3422 } 3423 3424 /** 3425 * Process page responses. 3426 * 3427 * @param lesson_page $page page object 3428 * @since Moodle 3.3 3429 */ 3430 public function process_page_responses(lesson_page $page) { 3431 $context = $this->get_context(); 3432 3433 // Check the page has answers [MDL-25632]. 3434 if (count($page->answers) > 0) { 3435 $result = $page->record_attempt($context); 3436 } else { 3437 // The page has no answers so we will just progress to the next page in the 3438 // sequence (as set by newpageid). 3439 $result = new stdClass; 3440 $result->newpageid = optional_param('newpageid', $page->nextpageid, PARAM_INT); 3441 $result->nodefaultresponse = true; 3442 $result->inmediatejump = false; 3443 } 3444 3445 if ($result->inmediatejump) { 3446 return $result; 3447 } 3448 3449 $result->newpageid = $this->calculate_new_page_on_jump($page, $result->newpageid); 3450 3451 return $result; 3452 } 3453 3454 /** 3455 * Add different informative messages to the given page. 3456 * 3457 * @param lesson_page $page page object 3458 * @param stdClass $result the page processing result object 3459 * @param bool $reviewmode whether we are in review mode or not 3460 * @since Moodle 3.3 3461 */ 3462 public function add_messages_on_page_process(lesson_page $page, $result, $reviewmode) { 3463 3464 if ($this->can_manage()) { 3465 // This is the warning msg for teachers to inform them that cluster and unseen does not work while logged in as a teacher. 3466 if (lesson_display_teacher_warning($this)) { 3467 $warningvars = new stdClass(); 3468 $warningvars->cluster = get_string("clusterjump", "lesson"); 3469 $warningvars->unseen = get_string("unseenpageinbranch", "lesson"); 3470 $this->add_message(get_string("teacherjumpwarning", "lesson", $warningvars)); 3471 } 3472 // Inform teacher that s/he will not see the timer. 3473 if ($this->properties->timelimit) { 3474 $this->add_message(get_string("teachertimerwarning", "lesson")); 3475 } 3476 } 3477 // Report attempts remaining. 3478 if ($result->attemptsremaining != 0 && $this->properties->review && !$reviewmode) { 3479 $this->add_message(get_string('attemptsremaining', 'lesson', $result->attemptsremaining)); 3480 } 3481 } 3482 3483 /** 3484 * Process and return all the information for the end of lesson page. 3485 * 3486 * @param string $outoftime used to check to see if the student ran out of time 3487 * @return stdclass an object with all the page data ready for rendering 3488 * @since Moodle 3.3 3489 */ 3490 public function process_eol_page($outoftime) { 3491 global $DB, $USER; 3492 3493 $course = $this->get_courserecord(); 3494 $cm = $this->get_cm(); 3495 $canmanage = $this->can_manage(); 3496 3497 // Init all the possible fields and values. 3498 $data = (object) array( 3499 'gradelesson' => true, 3500 'notenoughtimespent' => false, 3501 'numberofpagesviewed' => false, 3502 'youshouldview' => false, 3503 'numberofcorrectanswers' => false, 3504 'displayscorewithessays' => false, 3505 'displayscorewithoutessays' => false, 3506 'yourcurrentgradeisoutof' => false, 3507 'yourcurrentgradeis' => false, 3508 'eolstudentoutoftimenoanswers' => false, 3509 'welldone' => false, 3510 'progressbar' => false, 3511 'displayofgrade' => false, 3512 'reviewlesson' => false, 3513 'modattemptsnoteacher' => false, 3514 'activitylink' => false, 3515 'progresscompleted' => false, 3516 ); 3517 3518 $ntries = $DB->count_records("lesson_grades", array("lessonid" => $this->properties->id, "userid" => $USER->id)); 3519 if (isset($USER->modattempts[$this->properties->id])) { 3520 $ntries--; // Need to look at the old attempts :). 3521 } 3522 3523 $gradeinfo = lesson_grade($this, $ntries); 3524 $data->gradeinfo = $gradeinfo; 3525 if ($this->properties->custom && !$canmanage) { 3526 // Before we calculate the custom score make sure they answered the minimum 3527 // number of questions. We only need to do this for custom scoring as we can 3528 // not get the miniumum score the user should achieve. If we are not using 3529 // custom scoring (so all questions are valued as 1) then we simply check if 3530 // they answered more than the minimum questions, if not, we mark it out of the 3531 // number specified in the minimum questions setting - which is done in lesson_grade(). 3532 // Get the number of answers given. 3533 if ($gradeinfo->nquestions < $this->properties->minquestions) { 3534 $data->gradelesson = false; 3535 $a = new stdClass; 3536 $a->nquestions = $gradeinfo->nquestions; 3537 $a->minquestions = $this->properties->minquestions; 3538 $this->add_message(get_string('numberofpagesviewednotice', 'lesson', $a)); 3539 } 3540 } 3541 3542 if (!$canmanage) { 3543 if ($data->gradelesson) { 3544 // Store this now before any modifications to pages viewed. 3545 $progresscompleted = $this->calculate_progress(); 3546 3547 // Update the clock / get time information for this user. 3548 $this->stop_timer(); 3549 3550 // Update completion state. 3551 $completion = new completion_info($course); 3552 if ($completion->is_enabled($cm) && $this->properties->completionendreached) { 3553 $completion->update_state($cm, COMPLETION_COMPLETE); 3554 } 3555 3556 if ($this->properties->completiontimespent > 0) { 3557 $duration = $DB->get_field_sql( 3558 "SELECT SUM(lessontime - starttime) 3559 FROM {lesson_timer} 3560 WHERE lessonid = :lessonid 3561 AND userid = :userid", 3562 array('userid' => $USER->id, 'lessonid' => $this->properties->id)); 3563 if (!$duration) { 3564 $duration = 0; 3565 } 3566 3567 // If student has not spend enough time in the lesson, display a message. 3568 if ($duration < $this->properties->completiontimespent) { 3569 $a = new stdClass; 3570 $a->timespentraw = $duration; 3571 $a->timespent = format_time($duration); 3572 $a->timerequiredraw = $this->properties->completiontimespent; 3573 $a->timerequired = format_time($this->properties->completiontimespent); 3574 $data->notenoughtimespent = $a; 3575 } 3576 } 3577 3578 if ($gradeinfo->attempts) { 3579 if (!$this->properties->custom) { 3580 $data->numberofpagesviewed = $gradeinfo->nquestions; 3581 if ($this->properties->minquestions) { 3582 if ($gradeinfo->nquestions < $this->properties->minquestions) { 3583 $data->youshouldview = $this->properties->minquestions; 3584 } 3585 } 3586 $data->numberofcorrectanswers = $gradeinfo->earned; 3587 } 3588 $a = new stdClass; 3589 $a->score = $gradeinfo->earned; 3590 $a->grade = $gradeinfo->total; 3591 if ($gradeinfo->nmanual) { 3592 $a->tempmaxgrade = $gradeinfo->total - $gradeinfo->manualpoints; 3593 $a->essayquestions = $gradeinfo->nmanual; 3594 $data->displayscorewithessays = $a; 3595 } else { 3596 $data->displayscorewithoutessays = $a; 3597 } 3598 3599 $grade = new stdClass(); 3600 $grade->lessonid = $this->properties->id; 3601 $grade->userid = $USER->id; 3602 $grade->grade = $gradeinfo->grade; 3603 $grade->completed = time(); 3604 if (isset($USER->modattempts[$this->properties->id])) { // If reviewing, make sure update old grade record. 3605 if (!$grades = $DB->get_records("lesson_grades", 3606 array("lessonid" => $this->properties->id, "userid" => $USER->id), "completed DESC", '*', 0, 1)) { 3607 throw new moodle_exception('cannotfindgrade', 'lesson'); 3608 } 3609 $oldgrade = array_shift($grades); 3610 $grade->id = $oldgrade->id; 3611 $DB->update_record("lesson_grades", $grade); 3612 } else { 3613 $newgradeid = $DB->insert_record("lesson_grades", $grade); 3614 } 3615 3616 // Update central gradebook. 3617 lesson_update_grades($this, $USER->id); 3618 3619 // Print grade (grade type Point). 3620 if ($this->properties->grade > 0) { 3621 $a = new stdClass; 3622 $a->grade = format_float($gradeinfo->grade * $this->properties->grade / 100, 1); 3623 $a->total = $this->properties->grade; 3624 $data->yourcurrentgradeisoutof = $a; 3625 } 3626 3627 // Print grade (grade type Scale). 3628 if ($this->properties->grade < 0) { 3629 // Grade type is Scale. 3630 $grades = grade_get_grades($course->id, 'mod', 'lesson', $cm->instance, $USER->id); 3631 $grade = reset($grades->items[0]->grades); 3632 $data->yourcurrentgradeis = $grade->str_grade; 3633 } 3634 } else { 3635 if ($this->properties->timelimit) { 3636 if ($outoftime == 'normal') { 3637 $grade = new stdClass(); 3638 $grade->lessonid = $this->properties->id; 3639 $grade->userid = $USER->id; 3640 $grade->grade = 0; 3641 $grade->completed = time(); 3642 $newgradeid = $DB->insert_record("lesson_grades", $grade); 3643 $data->eolstudentoutoftimenoanswers = true; 3644 3645 // Update central gradebook. 3646 lesson_update_grades($this, $USER->id); 3647 } 3648 } else { 3649 $data->welldone = true; 3650 } 3651 } 3652 3653 $data->progresscompleted = $progresscompleted; 3654 } 3655 } else { 3656 // Display for teacher. 3657 if ($this->properties->grade != GRADE_TYPE_NONE) { 3658 $data->displayofgrade = true; 3659 } 3660 } 3661 3662 if ($this->properties->modattempts && !$canmanage) { 3663 // Make sure if the student is reviewing, that he/she sees the same pages/page path that he/she saw the first time 3664 // look at the attempt records to find the first QUESTION page that the user answered, then use that page id 3665 // to pass to view again. This is slick cause it wont call the empty($pageid) code 3666 // $ntries is decremented above. 3667 if (!$attempts = $this->get_attempts($ntries)) { 3668 $attempts = array(); 3669 $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id)); 3670 } else { 3671 $firstattempt = current($attempts); 3672 $pageid = $firstattempt->pageid; 3673 // If the student wishes to review, need to know the last question page that the student answered. 3674 // This will help to make sure that the student can leave the lesson via pushing the continue button. 3675 $lastattempt = end($attempts); 3676 $USER->modattempts[$this->properties->id] = $lastattempt->pageid; 3677 3678 $url = new moodle_url('/mod/lesson/view.php', array('id' => $cm->id, 'pageid' => $pageid)); 3679 } 3680 $data->reviewlesson = $url->out(false); 3681 } else if ($this->properties->modattempts && $canmanage) { 3682 $data->modattemptsnoteacher = true; 3683 } 3684 3685 if ($this->properties->activitylink) { 3686 $data->activitylink = $this->link_for_activitylink(); 3687 } 3688 return $data; 3689 } 3690 3691 /** 3692 * Returns the last "legal" attempt from the list of student attempts. 3693 * 3694 * @param array $attempts The list of student attempts. 3695 * @return stdClass The updated fom data. 3696 */ 3697 public function get_last_attempt(array $attempts): stdClass { 3698 // If there are more tries than the max that is allowed, grab the last "legal" attempt. 3699 if (!empty($this->maxattempts) && (count($attempts) > $this->maxattempts)) { 3700 $lastattempt = $attempts[$this->maxattempts - 1]; 3701 } else { 3702 // Grab the last attempt since there's no limit to the max attempts or the user has made fewer attempts than the max. 3703 $lastattempt = end($attempts); 3704 } 3705 return $lastattempt; 3706 } 3707 } 3708 3709 3710 /** 3711 * Abstract class to provide a core functions to the all lesson classes 3712 * 3713 * This class should be abstracted by ALL classes with the lesson module to ensure 3714 * that all classes within this module can be interacted with in the same way. 3715 * 3716 * This class provides the user with a basic properties array that can be fetched 3717 * or set via magic methods, or alternatively by defining methods get_blah() or 3718 * set_blah() within the extending object. 3719 * 3720 * @copyright 2009 Sam Hemelryk 3721 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3722 */ 3723 abstract class lesson_base { 3724 3725 /** 3726 * An object containing properties 3727 * @var stdClass 3728 */ 3729 protected $properties; 3730 3731 /** 3732 * The constructor 3733 * @param stdClass $properties 3734 */ 3735 public function __construct($properties) { 3736 $this->properties = (object)$properties; 3737 } 3738 3739 /** 3740 * Magic property method 3741 * 3742 * Attempts to call a set_$key method if one exists otherwise falls back 3743 * to simply set the property 3744 * 3745 * @param string $key 3746 * @param mixed $value 3747 */ 3748 public function __set($key, $value) { 3749 if (method_exists($this, 'set_'.$key)) { 3750 $this->{'set_'.$key}($value); 3751 } 3752 $this->properties->{$key} = $value; 3753 } 3754 3755 /** 3756 * Magic get method 3757 * 3758 * Attempts to call a get_$key method to return the property and ralls over 3759 * to return the raw property 3760 * 3761 * @param str $key 3762 * @return mixed 3763 */ 3764 public function __get($key) { 3765 if (method_exists($this, 'get_'.$key)) { 3766 return $this->{'get_'.$key}(); 3767 } 3768 return $this->properties->{$key}; 3769 } 3770 3771 /** 3772 * Stupid PHP needs an isset magic method if you use the get magic method and 3773 * still want empty calls to work.... blah ~! 3774 * 3775 * @param string $key 3776 * @return bool 3777 */ 3778 public function __isset($key) { 3779 if (method_exists($this, 'get_'.$key)) { 3780 $val = $this->{'get_'.$key}(); 3781 return !empty($val); 3782 } 3783 return !empty($this->properties->{$key}); 3784 } 3785 3786 //NOTE: E_STRICT does not allow to change function signature! 3787 3788 /** 3789 * If implemented should create a new instance, save it in the DB and return it 3790 */ 3791 //public static function create() {} 3792 /** 3793 * If implemented should load an instance from the DB and return it 3794 */ 3795 //public static function load() {} 3796 /** 3797 * Fetches all of the properties of the object 3798 * @return stdClass 3799 */ 3800 public function properties() { 3801 return $this->properties; 3802 } 3803 } 3804 3805 3806 /** 3807 * Abstract class representation of a page associated with a lesson. 3808 * 3809 * This class should MUST be extended by all specialised page types defined in 3810 * mod/lesson/pagetypes/. 3811 * There are a handful of abstract methods that need to be defined as well as 3812 * severl methods that can optionally be defined in order to make the page type 3813 * operate in the desired way 3814 * 3815 * Database properties 3816 * @property int $id The id of this lesson page 3817 * @property int $lessonid The id of the lesson this page belongs to 3818 * @property int $prevpageid The id of the page before this one 3819 * @property int $nextpageid The id of the next page in the page sequence 3820 * @property int $qtype Identifies the page type of this page 3821 * @property int $qoption Used to record page type specific options 3822 * @property int $layout Used to record page specific layout selections 3823 * @property int $display Used to record page specific display selections 3824 * @property int $timecreated Timestamp for when the page was created 3825 * @property int $timemodified Timestamp for when the page was last modified 3826 * @property string $title The title of this page 3827 * @property string $contents The rich content shown to describe the page 3828 * @property int $contentsformat The format of the contents field 3829 * 3830 * Calculated properties 3831 * @property-read array $answers An array of answers for this page 3832 * @property-read bool $displayinmenublock Toggles display in the left menu block 3833 * @property-read array $jumps An array containing all the jumps this page uses 3834 * @property-read lesson $lesson The lesson this page belongs to 3835 * @property-read int $type The type of the page [question | structure] 3836 * @property-read typeid The unique identifier for the page type 3837 * @property-read typestring The string that describes this page type 3838 * 3839 * @abstract 3840 * @copyright 2009 Sam Hemelryk 3841 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 3842 */ 3843 abstract class lesson_page extends lesson_base { 3844 3845 /** 3846 * A reference to the lesson this page belongs to 3847 * @var lesson 3848 */ 3849 protected $lesson = null; 3850 /** 3851 * Contains the answers to this lesson_page once loaded 3852 * @var null|array 3853 */ 3854 protected $answers = null; 3855 /** 3856 * This sets the type of the page, can be one of the constants defined below 3857 * @var int 3858 */ 3859 protected $type = 0; 3860 3861 /** 3862 * Constants used to identify the type of the page 3863 */ 3864 const TYPE_QUESTION = 0; 3865 const TYPE_STRUCTURE = 1; 3866 3867 /** 3868 * Constant used as a delimiter when parsing multianswer questions 3869 */ 3870 const MULTIANSWER_DELIMITER = '@^#|'; 3871 3872 /** 3873 * This method should return the integer used to identify the page type within 3874 * the database and throughout code. This maps back to the defines used in 1.x 3875 * @abstract 3876 * @return int 3877 */ 3878 abstract protected function get_typeid(); 3879 /** 3880 * This method should return the string that describes the pagetype 3881 * @abstract 3882 * @return string 3883 */ 3884 abstract protected function get_typestring(); 3885 3886 /** 3887 * This method gets called to display the page to the user taking the lesson 3888 * @abstract 3889 * @param object $renderer 3890 * @param object $attempt 3891 * @return string 3892 */ 3893 abstract public function display($renderer, $attempt); 3894 3895 /** 3896 * Creates a new lesson_page within the database and returns the correct pagetype 3897 * object to use to interact with the new lesson 3898 * 3899 * @final 3900 * @static 3901 * @param object $properties 3902 * @param lesson $lesson 3903 * @return lesson_page Specialised object that extends lesson_page 3904 */ 3905 final public static function create($properties, lesson $lesson, $context, $maxbytes) { 3906 global $DB; 3907 $newpage = new stdClass; 3908 $newpage->title = $properties->title; 3909 $newpage->contents = $properties->contents_editor['text']; 3910 $newpage->contentsformat = $properties->contents_editor['format']; 3911 $newpage->lessonid = $lesson->id; 3912 $newpage->timecreated = time(); 3913 $newpage->qtype = $properties->qtype; 3914 $newpage->qoption = (isset($properties->qoption))?1:0; 3915 $newpage->layout = (isset($properties->layout))?1:0; 3916 $newpage->display = (isset($properties->display))?1:0; 3917 $newpage->prevpageid = 0; // this is a first page 3918 $newpage->nextpageid = 0; // this is the only page 3919 3920 if ($properties->pageid) { 3921 $prevpage = $DB->get_record("lesson_pages", array("id" => $properties->pageid), 'id, nextpageid'); 3922 if (!$prevpage) { 3923 throw new \moodle_exception('cannotfindpages', 'lesson'); 3924 } 3925 $newpage->prevpageid = $prevpage->id; 3926 $newpage->nextpageid = $prevpage->nextpageid; 3927 } else { 3928 $nextpage = $DB->get_record('lesson_pages', array('lessonid'=>$lesson->id, 'prevpageid'=>0), 'id'); 3929 if ($nextpage) { 3930 // This is the first page, there are existing pages put this at the start 3931 $newpage->nextpageid = $nextpage->id; 3932 } 3933 } 3934 3935 $newpage->id = $DB->insert_record("lesson_pages", $newpage); 3936 3937 $editor = new stdClass; 3938 $editor->id = $newpage->id; 3939 $editor->contents_editor = $properties->contents_editor; 3940 $editor = file_postupdate_standard_editor($editor, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $editor->id); 3941 $DB->update_record("lesson_pages", $editor); 3942 3943 if ($newpage->prevpageid > 0) { 3944 $DB->set_field("lesson_pages", "nextpageid", $newpage->id, array("id" => $newpage->prevpageid)); 3945 } 3946 if ($newpage->nextpageid > 0) { 3947 $DB->set_field("lesson_pages", "prevpageid", $newpage->id, array("id" => $newpage->nextpageid)); 3948 } 3949 3950 $page = lesson_page::load($newpage, $lesson); 3951 $page->create_answers($properties); 3952 3953 // Trigger an event: page created. 3954 $eventparams = array( 3955 'context' => $context, 3956 'objectid' => $newpage->id, 3957 'other' => array( 3958 'pagetype' => $page->get_typestring() 3959 ) 3960 ); 3961 $event = \mod_lesson\event\page_created::create($eventparams); 3962 $snapshot = clone($newpage); 3963 $snapshot->timemodified = 0; 3964 $event->add_record_snapshot('lesson_pages', $snapshot); 3965 $event->trigger(); 3966 3967 $lesson->add_message(get_string('insertedpage', 'lesson').': '.format_string($newpage->title, true), 'notifysuccess'); 3968 3969 return $page; 3970 } 3971 3972 /** 3973 * This method loads a page object from the database and returns it as a 3974 * specialised object that extends lesson_page 3975 * 3976 * @final 3977 * @static 3978 * @param int $id 3979 * @param lesson $lesson 3980 * @return lesson_page Specialised lesson_page object 3981 */ 3982 final public static function load($id, lesson $lesson) { 3983 global $DB; 3984 3985 if (is_object($id) && !empty($id->qtype)) { 3986 $page = $id; 3987 } else { 3988 $page = $DB->get_record("lesson_pages", array("id" => $id)); 3989 if (!$page) { 3990 throw new \moodle_exception('cannotfindpages', 'lesson'); 3991 } 3992 } 3993 $manager = lesson_page_type_manager::get($lesson); 3994 3995 $class = 'lesson_page_type_'.$manager->get_page_type_idstring($page->qtype); 3996 if (!class_exists($class)) { 3997 $class = 'lesson_page'; 3998 } 3999 4000 return new $class($page, $lesson); 4001 } 4002 4003 /** 4004 * Deletes a lesson_page from the database as well as any associated records. 4005 * @final 4006 * @return bool 4007 */ 4008 final public function delete() { 4009 global $DB; 4010 4011 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course); 4012 $context = context_module::instance($cm->id); 4013 4014 // Delete files associated with attempts. 4015 $fs = get_file_storage(); 4016 if ($attempts = $DB->get_records('lesson_attempts', array("pageid" => $this->properties->id))) { 4017 foreach ($attempts as $attempt) { 4018 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses', $attempt->id); 4019 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_answers', $attempt->id); 4020 } 4021 } 4022 4023 // Then delete all the associated records... 4024 $DB->delete_records("lesson_attempts", array("pageid" => $this->properties->id)); 4025 4026 $DB->delete_records("lesson_branch", array("pageid" => $this->properties->id)); 4027 4028 // Delete files related to answers and responses. 4029 if ($answers = $DB->get_records("lesson_answers", array("pageid" => $this->properties->id))) { 4030 foreach ($answers as $answer) { 4031 $fs->delete_area_files($context->id, 'mod_lesson', 'page_answers', $answer->id); 4032 $fs->delete_area_files($context->id, 'mod_lesson', 'page_responses', $answer->id); 4033 } 4034 } 4035 4036 // ...now delete the answers... 4037 $DB->delete_records("lesson_answers", array("pageid" => $this->properties->id)); 4038 // ..and the page itself 4039 $DB->delete_records("lesson_pages", array("id" => $this->properties->id)); 4040 4041 // Trigger an event: page deleted. 4042 $eventparams = array( 4043 'context' => $context, 4044 'objectid' => $this->properties->id, 4045 'other' => array( 4046 'pagetype' => $this->get_typestring() 4047 ) 4048 ); 4049 $event = \mod_lesson\event\page_deleted::create($eventparams); 4050 $event->add_record_snapshot('lesson_pages', $this->properties); 4051 $event->trigger(); 4052 4053 // Delete files associated with this page. 4054 $fs->delete_area_files($context->id, 'mod_lesson', 'page_contents', $this->properties->id); 4055 4056 // repair the hole in the linkage 4057 if (!$this->properties->prevpageid && !$this->properties->nextpageid) { 4058 //This is the only page, no repair needed 4059 } elseif (!$this->properties->prevpageid) { 4060 // this is the first page... 4061 $page = $this->lesson->load_page($this->properties->nextpageid); 4062 $page->move(null, 0); 4063 } elseif (!$this->properties->nextpageid) { 4064 // this is the last page... 4065 $page = $this->lesson->load_page($this->properties->prevpageid); 4066 $page->move(0); 4067 } else { 4068 // page is in the middle... 4069 $prevpage = $this->lesson->load_page($this->properties->prevpageid); 4070 $nextpage = $this->lesson->load_page($this->properties->nextpageid); 4071 4072 $prevpage->move($nextpage->id); 4073 $nextpage->move(null, $prevpage->id); 4074 } 4075 return true; 4076 } 4077 4078 /** 4079 * Moves a page by updating its nextpageid and prevpageid values within 4080 * the database 4081 * 4082 * @final 4083 * @param int $nextpageid 4084 * @param int $prevpageid 4085 */ 4086 final public function move($nextpageid=null, $prevpageid=null) { 4087 global $DB; 4088 if ($nextpageid === null) { 4089 $nextpageid = $this->properties->nextpageid; 4090 } 4091 if ($prevpageid === null) { 4092 $prevpageid = $this->properties->prevpageid; 4093 } 4094 $obj = new stdClass; 4095 $obj->id = $this->properties->id; 4096 $obj->prevpageid = $prevpageid; 4097 $obj->nextpageid = $nextpageid; 4098 $DB->update_record('lesson_pages', $obj); 4099 } 4100 4101 /** 4102 * Returns the answers that are associated with this page in the database 4103 * 4104 * @final 4105 * @return array 4106 */ 4107 final public function get_answers() { 4108 global $DB; 4109 if ($this->answers === null) { 4110 $this->answers = array(); 4111 $answers = $DB->get_records('lesson_answers', array('pageid'=>$this->properties->id, 'lessonid'=>$this->lesson->id), 'id'); 4112 if (!$answers) { 4113 // It is possible that a lesson upgraded from Moodle 1.9 still 4114 // contains questions without any answers [MDL-25632]. 4115 // debugging(get_string('cannotfindanswer', 'lesson')); 4116 return array(); 4117 } 4118 foreach ($answers as $answer) { 4119 $this->answers[count($this->answers)] = new lesson_page_answer($answer); 4120 } 4121 } 4122 return $this->answers; 4123 } 4124 4125 /** 4126 * Returns the lesson this page is associated with 4127 * @final 4128 * @return lesson 4129 */ 4130 final protected function get_lesson() { 4131 return $this->lesson; 4132 } 4133 4134 /** 4135 * Returns the type of page this is. Not to be confused with page type 4136 * @final 4137 * @return int 4138 */ 4139 final protected function get_type() { 4140 return $this->type; 4141 } 4142 4143 /** 4144 * Records an attempt at this page 4145 * 4146 * @final 4147 * @global moodle_database $DB 4148 * @param stdClass $context 4149 * @return stdClass Returns the result of the attempt 4150 */ 4151 final public function record_attempt($context) { 4152 global $DB, $USER, $OUTPUT, $PAGE; 4153 4154 /** 4155 * This should be overridden by each page type to actually check the response 4156 * against what ever custom criteria they have defined 4157 */ 4158 $result = $this->check_answer(); 4159 4160 // Processes inmediate jumps. 4161 if ($result->inmediatejump) { 4162 return $result; 4163 } 4164 4165 $result->attemptsremaining = 0; 4166 $result->maxattemptsreached = false; 4167 4168 if ($result->noanswer) { 4169 $result->newpageid = $this->properties->id; // display same page again 4170 $result->feedback = get_string('noanswer', 'lesson'); 4171 } else { 4172 if (!has_capability('mod/lesson:manage', $context)) { 4173 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id)); 4174 4175 // Get the number of attempts that have been made on this question for this student and retake, 4176 $nattempts = $DB->count_records('lesson_attempts', array('lessonid' => $this->lesson->id, 4177 'userid' => $USER->id, 'pageid' => $this->properties->id, 'retry' => $nretakes)); 4178 4179 // Check if they have reached (or exceeded) the maximum number of attempts allowed. 4180 if (!empty($this->lesson->maxattempts) && $nattempts >= $this->lesson->maxattempts) { 4181 $result->maxattemptsreached = true; 4182 $result->feedback = get_string('maximumnumberofattemptsreached', 'lesson'); 4183 $result->newpageid = $this->lesson->get_next_page($this->properties->nextpageid); 4184 return $result; 4185 } 4186 4187 // record student's attempt 4188 $attempt = new stdClass; 4189 $attempt->lessonid = $this->lesson->id; 4190 $attempt->pageid = $this->properties->id; 4191 $attempt->userid = $USER->id; 4192 $attempt->answerid = $result->answerid; 4193 $attempt->retry = $nretakes; 4194 $attempt->correct = $result->correctanswer; 4195 if($result->userresponse !== null) { 4196 $attempt->useranswer = $result->userresponse; 4197 } 4198 4199 $attempt->timeseen = time(); 4200 // if allow modattempts, then update the old attempt record, otherwise, insert new answer record 4201 $userisreviewing = false; 4202 if (isset($USER->modattempts[$this->lesson->id])) { 4203 $attempt->retry = $nretakes - 1; // they are going through on review, $nretakes will be too high 4204 $userisreviewing = true; 4205 } 4206 4207 // Only insert a record if we are not reviewing the lesson. 4208 if (!$userisreviewing) { 4209 if ($this->lesson->retake || (!$this->lesson->retake && $nretakes == 0)) { 4210 $attempt->id = $DB->insert_record("lesson_attempts", $attempt); 4211 4212 list($updatedattempt, $updatedresult) = $this->on_after_write_attempt($attempt, $result); 4213 if ($updatedattempt) { 4214 $attempt = $updatedattempt; 4215 $result = $updatedresult; 4216 $DB->update_record("lesson_attempts", $attempt); 4217 } 4218 4219 // Trigger an event: question answered. 4220 $eventparams = array( 4221 'context' => context_module::instance($PAGE->cm->id), 4222 'objectid' => $this->properties->id, 4223 'other' => array( 4224 'pagetype' => $this->get_typestring() 4225 ) 4226 ); 4227 $event = \mod_lesson\event\question_answered::create($eventparams); 4228 $event->add_record_snapshot('lesson_attempts', $attempt); 4229 $event->trigger(); 4230 4231 // Increase the number of attempts made. 4232 $nattempts++; 4233 } 4234 } else { 4235 // When reviewing the lesson, the existing attemptid is also needed for the filearea options. 4236 $params = [ 4237 'lessonid' => $attempt->lessonid, 4238 'pageid' => $attempt->pageid, 4239 'userid' => $attempt->userid, 4240 'answerid' => $attempt->answerid, 4241 'retry' => $attempt->retry 4242 ]; 4243 $attempt->id = $DB->get_field('lesson_attempts', 'id', $params); 4244 } 4245 // "number of attempts remaining" message if $this->lesson->maxattempts > 1 4246 // displaying of message(s) is at the end of page for more ergonomic display 4247 // If we are showing the number of remaining attempts, we need to show it regardless of what the next 4248 // jump to page is. 4249 if (!$result->correctanswer) { 4250 // Retrieve the number of attempts left counter for displaying at bottom of feedback page. 4251 if ($result->newpageid == 0 && !empty($this->lesson->maxattempts) && $nattempts >= $this->lesson->maxattempts) { 4252 if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt 4253 $result->maxattemptsreached = true; 4254 } 4255 $result->newpageid = LESSON_NEXTPAGE; 4256 } else if ($this->lesson->maxattempts > 1) { // don't bother with message if only one attempt 4257 $result->attemptsremaining = $this->lesson->maxattempts - $nattempts; 4258 if ($result->attemptsremaining == 0) { 4259 $result->maxattemptsreached = true; 4260 } 4261 } 4262 } 4263 } 4264 4265 // Determine default feedback if necessary 4266 if (empty($result->response)) { 4267 if (!$this->lesson->feedback && !$result->noanswer && !($this->lesson->review & !$result->correctanswer && !$result->isessayquestion)) { 4268 // These conditions have been met: 4269 // 1. The lesson manager has not supplied feedback to the student 4270 // 2. Not displaying default feedback 4271 // 3. The user did provide an answer 4272 // 4. We are not reviewing with an incorrect answer (and not reviewing an essay question) 4273 4274 $result->nodefaultresponse = true; // This will cause a redirect below 4275 } else if ($result->isessayquestion) { 4276 $result->response = get_string('defaultessayresponse', 'lesson'); 4277 } else if ($result->correctanswer) { 4278 $result->response = get_string('thatsthecorrectanswer', 'lesson'); 4279 } else { 4280 $result->response = get_string('thatsthewronganswer', 'lesson'); 4281 } 4282 } 4283 4284 if ($result->response) { 4285 if ($this->lesson->review && !$result->correctanswer && !$result->isessayquestion) { 4286 $nretakes = $DB->count_records("lesson_grades", array("lessonid"=>$this->lesson->id, "userid"=>$USER->id)); 4287 $qattempts = $DB->count_records("lesson_attempts", array("userid"=>$USER->id, "retry"=>$nretakes, "pageid"=>$this->properties->id)); 4288 if ($qattempts == 1) { 4289 $result->feedback = $OUTPUT->box(get_string("firstwrong", "lesson"), 'feedback'); 4290 } else { 4291 if (!$result->maxattemptsreached) { 4292 $result->feedback = $OUTPUT->box(get_string("secondpluswrong", "lesson"), 'feedback'); 4293 } else { 4294 $result->feedback = $OUTPUT->box(get_string("finalwrong", "lesson"), 'feedback'); 4295 } 4296 } 4297 } else { 4298 $result->feedback = ''; 4299 } 4300 $class = 'response'; 4301 if ($result->correctanswer) { 4302 $class .= ' correct'; // CSS over-ride this if they exist (!important). 4303 } else if (!$result->isessayquestion) { 4304 $class .= ' incorrect'; // CSS over-ride this if they exist (!important). 4305 } 4306 $options = new stdClass; 4307 $options->noclean = true; 4308 $options->para = true; 4309 $options->overflowdiv = true; 4310 $options->context = $context; 4311 $options->attemptid = isset($attempt) ? $attempt->id : null; 4312 4313 $result->feedback .= $OUTPUT->box(format_text($this->get_contents(), $this->properties->contentsformat, $options), 4314 'generalbox boxaligncenter py-3'); 4315 $result->feedback .= '<div class="correctanswer generalbox"><em>' 4316 . get_string("youranswer", "lesson").'</em> : <div class="studentanswer mt-2 mb-2">'; 4317 4318 // Create a table containing the answers and responses. 4319 $table = new html_table(); 4320 // Multianswer allowed. 4321 if ($this->properties->qoption) { 4322 $studentanswerarray = explode(self::MULTIANSWER_DELIMITER, $result->studentanswer); 4323 $responsearr = explode(self::MULTIANSWER_DELIMITER, $result->response); 4324 $studentanswerresponse = array_combine($studentanswerarray, $responsearr); 4325 4326 foreach ($studentanswerresponse as $answer => $response) { 4327 // Add a table row containing the answer. 4328 $studentanswer = $this->format_answer($answer, $context, $result->studentanswerformat, $options); 4329 $table->data[] = array($studentanswer); 4330 // If the response exists, add a table row containing the response. If not, add en empty row. 4331 if (!empty(trim($response))) { 4332 $studentresponse = isset($result->responseformat) ? 4333 $this->format_response($response, $context, $result->responseformat, $options) : $response; 4334 $studentresponsecontent = html_writer::div('<em>' . get_string("response", "lesson") . 4335 '</em>: <br/>' . $studentresponse, $class); 4336 $table->data[] = array($studentresponsecontent); 4337 } else { 4338 $table->data[] = array(''); 4339 } 4340 } 4341 } else { 4342 // Add a table row containing the answer. 4343 $studentanswer = $this->format_answer($result->studentanswer, $context, $result->studentanswerformat, $options); 4344 $table->data[] = array($studentanswer); 4345 // If the response exists, add a table row containing the response. If not, add en empty row. 4346 if (!empty(trim($result->response))) { 4347 $studentresponse = isset($result->responseformat) ? 4348 $this->format_response($result->response, $context, $result->responseformat, 4349 $result->answerid, $options) : $result->response; 4350 $studentresponsecontent = html_writer::div('<em>' . get_string("response", "lesson") . 4351 '</em>: <br/>' . $studentresponse, $class); 4352 $table->data[] = array($studentresponsecontent); 4353 } else { 4354 $table->data[] = array(''); 4355 } 4356 } 4357 4358 $result->feedback .= html_writer::table($table).'</div></div>'; 4359 } 4360 } 4361 return $result; 4362 } 4363 4364 /** 4365 * Formats the answer. Override for custom formatting. 4366 * 4367 * @param string $answer 4368 * @param context $context 4369 * @param int $answerformat 4370 * @return string Returns formatted string 4371 */ 4372 public function format_answer($answer, $context, $answerformat, $options = []) { 4373 4374 if (is_object($options)) { 4375 $options = (array) $options; 4376 } 4377 4378 if (empty($options['context'])) { 4379 $options['context'] = $context; 4380 } 4381 4382 if (empty($options['para'])) { 4383 $options['para'] = true; 4384 } 4385 4386 return format_text($answer, $answerformat, $options); 4387 } 4388 4389 /** 4390 * Formats the response 4391 * 4392 * @param string $response 4393 * @param context $context 4394 * @param int $responseformat 4395 * @param int $answerid 4396 * @param stdClass $options 4397 * @return string Returns formatted string 4398 */ 4399 private function format_response($response, $context, $responseformat, $answerid, $options) { 4400 4401 $convertstudentresponse = file_rewrite_pluginfile_urls($response, 'pluginfile.php', 4402 $context->id, 'mod_lesson', 'page_responses', $answerid); 4403 4404 return format_text($convertstudentresponse, $responseformat, $options); 4405 } 4406 4407 /** 4408 * Returns the string for a jump name 4409 * 4410 * @final 4411 * @param int $jumpto Jump code or page ID 4412 * @return string 4413 **/ 4414 final protected function get_jump_name($jumpto) { 4415 global $DB; 4416 static $jumpnames = array(); 4417 4418 if (!array_key_exists($jumpto, $jumpnames)) { 4419 if ($jumpto == LESSON_THISPAGE) { 4420 $jumptitle = get_string('thispage', 'lesson'); 4421 } elseif ($jumpto == LESSON_NEXTPAGE) { 4422 $jumptitle = get_string('nextpage', 'lesson'); 4423 } elseif ($jumpto == LESSON_EOL) { 4424 $jumptitle = get_string('endoflesson', 'lesson'); 4425 } elseif ($jumpto == LESSON_UNSEENBRANCHPAGE) { 4426 $jumptitle = get_string('unseenpageinbranch', 'lesson'); 4427 } elseif ($jumpto == LESSON_PREVIOUSPAGE) { 4428 $jumptitle = get_string('previouspage', 'lesson'); 4429 } elseif ($jumpto == LESSON_RANDOMPAGE) { 4430 $jumptitle = get_string('randompageinbranch', 'lesson'); 4431 } elseif ($jumpto == LESSON_RANDOMBRANCH) { 4432 $jumptitle = get_string('randombranch', 'lesson'); 4433 } elseif ($jumpto == LESSON_CLUSTERJUMP) { 4434 $jumptitle = get_string('clusterjump', 'lesson'); 4435 } else { 4436 if (!$jumptitle = $DB->get_field('lesson_pages', 'title', array('id' => $jumpto))) { 4437 $jumptitle = '<strong>'.get_string('notdefined', 'lesson').'</strong>'; 4438 } 4439 } 4440 $jumpnames[$jumpto] = format_string($jumptitle,true); 4441 } 4442 4443 return $jumpnames[$jumpto]; 4444 } 4445 4446 /** 4447 * Constructor method 4448 * @param object $properties 4449 * @param lesson $lesson 4450 */ 4451 public function __construct($properties, lesson $lesson) { 4452 parent::__construct($properties); 4453 $this->lesson = $lesson; 4454 } 4455 4456 /** 4457 * Returns the score for the attempt 4458 * This may be overridden by page types that require manual grading 4459 * @param array $answers 4460 * @param object $attempt 4461 * @return int 4462 */ 4463 public function earned_score($answers, $attempt) { 4464 return $answers[$attempt->answerid]->score; 4465 } 4466 4467 /** 4468 * This is a callback method that can be override and gets called when ever a page 4469 * is viewed 4470 * 4471 * @param bool $canmanage True if the user has the manage cap 4472 * @param bool $redirect Optional, default to true. Set to false to avoid redirection and return the page to redirect. 4473 * @return mixed 4474 */ 4475 public function callback_on_view($canmanage, $redirect = true) { 4476 return true; 4477 } 4478 4479 /** 4480 * save editor answers files and update answer record 4481 * 4482 * @param object $context 4483 * @param int $maxbytes 4484 * @param object $answer 4485 * @param object $answereditor 4486 * @param object $responseeditor 4487 */ 4488 public function save_answers_files($context, $maxbytes, &$answer, $answereditor = '', $responseeditor = '') { 4489 global $DB; 4490 if (isset($answereditor['itemid'])) { 4491 $answer->answer = file_save_draft_area_files($answereditor['itemid'], 4492 $context->id, 'mod_lesson', 'page_answers', $answer->id, 4493 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes), 4494 $answer->answer, null); 4495 $DB->set_field('lesson_answers', 'answer', $answer->answer, array('id' => $answer->id)); 4496 } 4497 if (isset($responseeditor['itemid'])) { 4498 $answer->response = file_save_draft_area_files($responseeditor['itemid'], 4499 $context->id, 'mod_lesson', 'page_responses', $answer->id, 4500 array('noclean' => true, 'maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $maxbytes), 4501 $answer->response, null); 4502 $DB->set_field('lesson_answers', 'response', $answer->response, array('id' => $answer->id)); 4503 } 4504 } 4505 4506 /** 4507 * Rewrite urls in response and optionality answer of a question answer 4508 * 4509 * @param object $answer 4510 * @param bool $rewriteanswer must rewrite answer 4511 * @return object answer with rewritten urls 4512 */ 4513 public static function rewrite_answers_urls($answer, $rewriteanswer = true) { 4514 global $PAGE; 4515 4516 $context = context_module::instance($PAGE->cm->id); 4517 if ($rewriteanswer) { 4518 $answer->answer = file_rewrite_pluginfile_urls($answer->answer, 'pluginfile.php', $context->id, 4519 'mod_lesson', 'page_answers', $answer->id); 4520 } 4521 $answer->response = file_rewrite_pluginfile_urls($answer->response, 'pluginfile.php', $context->id, 4522 'mod_lesson', 'page_responses', $answer->id); 4523 4524 return $answer; 4525 } 4526 4527 /** 4528 * Updates a lesson page and its answers within the database 4529 * 4530 * @param object $properties 4531 * @return bool 4532 */ 4533 public function update($properties, $context = null, $maxbytes = null) { 4534 global $DB, $PAGE; 4535 $answers = $this->get_answers(); 4536 $properties->id = $this->properties->id; 4537 $properties->lessonid = $this->lesson->id; 4538 if (empty($properties->qoption)) { 4539 $properties->qoption = '0'; 4540 } 4541 if (empty($context)) { 4542 $context = $PAGE->context; 4543 } 4544 if ($maxbytes === null) { 4545 $maxbytes = get_user_max_upload_file_size($context); 4546 } 4547 $properties->timemodified = time(); 4548 $properties = file_postupdate_standard_editor($properties, 'contents', array('noclean'=>true, 'maxfiles'=>EDITOR_UNLIMITED_FILES, 'maxbytes'=>$maxbytes), $context, 'mod_lesson', 'page_contents', $properties->id); 4549 $DB->update_record("lesson_pages", $properties); 4550 4551 // Trigger an event: page updated. 4552 \mod_lesson\event\page_updated::create_from_lesson_page($this, $context)->trigger(); 4553 4554 if ($this->type == self::TYPE_STRUCTURE && $this->get_typeid() != LESSON_PAGE_BRANCHTABLE) { 4555 // These page types have only one answer to save the jump and score. 4556 if (count($answers) > 1) { 4557 $answer = array_shift($answers); 4558 foreach ($answers as $a) { 4559 $DB->delete_records('lesson_answers', array('id' => $a->id)); 4560 } 4561 } else if (count($answers) == 1) { 4562 $answer = array_shift($answers); 4563 } else { 4564 $answer = new stdClass; 4565 $answer->lessonid = $properties->lessonid; 4566 $answer->pageid = $properties->id; 4567 $answer->timecreated = time(); 4568 } 4569 4570 $answer->timemodified = time(); 4571 if (isset($properties->jumpto[0])) { 4572 $answer->jumpto = $properties->jumpto[0]; 4573 } 4574 if (isset($properties->score[0])) { 4575 $answer->score = $properties->score[0]; 4576 } 4577 if (!empty($answer->id)) { 4578 $DB->update_record("lesson_answers", $answer->properties()); 4579 } else { 4580 $DB->insert_record("lesson_answers", $answer); 4581 } 4582 } else { 4583 for ($i = 0; $i < count($properties->answer_editor); $i++) { 4584 if (!array_key_exists($i, $this->answers)) { 4585 $this->answers[$i] = new stdClass; 4586 $this->answers[$i]->lessonid = $this->lesson->id; 4587 $this->answers[$i]->pageid = $this->id; 4588 $this->answers[$i]->timecreated = $this->timecreated; 4589 $this->answers[$i]->answer = null; 4590 } 4591 4592 if (isset($properties->answer_editor[$i])) { 4593 if (is_array($properties->answer_editor[$i])) { 4594 // Multichoice and true/false pages have an HTML editor. 4595 $this->answers[$i]->answer = $properties->answer_editor[$i]['text']; 4596 $this->answers[$i]->answerformat = $properties->answer_editor[$i]['format']; 4597 } else { 4598 // Branch tables, shortanswer and mumerical pages have only a text field. 4599 $this->answers[$i]->answer = $properties->answer_editor[$i]; 4600 $this->answers[$i]->answerformat = FORMAT_MOODLE; 4601 } 4602 } else { 4603 // If there is no data posted which means we want to reset the stored values. 4604 $this->answers[$i]->answer = null; 4605 } 4606 4607 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) { 4608 $this->answers[$i]->response = $properties->response_editor[$i]['text']; 4609 $this->answers[$i]->responseformat = $properties->response_editor[$i]['format']; 4610 } 4611 4612 if ($this->answers[$i]->answer !== null && $this->answers[$i]->answer !== '') { 4613 if (isset($properties->jumpto[$i])) { 4614 $this->answers[$i]->jumpto = $properties->jumpto[$i]; 4615 } 4616 if ($this->lesson->custom && isset($properties->score[$i])) { 4617 $this->answers[$i]->score = $properties->score[$i]; 4618 } 4619 if (!isset($this->answers[$i]->id)) { 4620 $this->answers[$i]->id = $DB->insert_record("lesson_answers", $this->answers[$i]); 4621 } else { 4622 $DB->update_record("lesson_answers", $this->answers[$i]->properties()); 4623 } 4624 4625 // Save files in answers and responses. 4626 if (isset($properties->response_editor[$i])) { 4627 $this->save_answers_files($context, $maxbytes, $this->answers[$i], 4628 $properties->answer_editor[$i], $properties->response_editor[$i]); 4629 } else { 4630 $this->save_answers_files($context, $maxbytes, $this->answers[$i], 4631 $properties->answer_editor[$i]); 4632 } 4633 4634 } else if (isset($this->answers[$i]->id)) { 4635 $DB->delete_records('lesson_answers', array('id' => $this->answers[$i]->id)); 4636 unset($this->answers[$i]); 4637 } 4638 } 4639 } 4640 return true; 4641 } 4642 4643 /** 4644 * Can be set to true if the page requires a static link to create a new instance 4645 * instead of simply being included in the dropdown 4646 * @param int $previd 4647 * @return bool 4648 */ 4649 public function add_page_link($previd) { 4650 return false; 4651 } 4652 4653 /** 4654 * Returns true if a page has been viewed before 4655 * 4656 * @param array|int $param Either an array of pages that have been seen or the 4657 * number of retakes a user has had 4658 * @return bool 4659 */ 4660 public function is_unseen($param) { 4661 global $USER, $DB; 4662 if (is_array($param)) { 4663 $seenpages = $param; 4664 return (!array_key_exists($this->properties->id, $seenpages)); 4665 } else { 4666 $nretakes = $param; 4667 if (!$DB->count_records("lesson_attempts", array("pageid"=>$this->properties->id, "userid"=>$USER->id, "retry"=>$nretakes))) { 4668 return true; 4669 } 4670 } 4671 return false; 4672 } 4673 4674 /** 4675 * Checks to see if a page has been answered previously 4676 * @param int $nretakes 4677 * @return bool 4678 */ 4679 public function is_unanswered($nretakes) { 4680 global $DB, $USER; 4681 if (!$DB->count_records("lesson_attempts", array('pageid'=>$this->properties->id, 'userid'=>$USER->id, 'correct'=>1, 'retry'=>$nretakes))) { 4682 return true; 4683 } 4684 return false; 4685 } 4686 4687 /** 4688 * Creates answers within the database for this lesson_page. Usually only ever 4689 * called when creating a new page instance 4690 * @param object $properties 4691 * @return array 4692 */ 4693 public function create_answers($properties) { 4694 global $DB, $PAGE; 4695 // now add the answers 4696 $newanswer = new stdClass; 4697 $newanswer->lessonid = $this->lesson->id; 4698 $newanswer->pageid = $this->properties->id; 4699 $newanswer->timecreated = $this->properties->timecreated; 4700 4701 $cm = get_coursemodule_from_instance('lesson', $this->lesson->id, $this->lesson->course); 4702 $context = context_module::instance($cm->id); 4703 4704 $answers = array(); 4705 4706 for ($i = 0; $i < ($this->lesson->maxanswers + 1); $i++) { 4707 $answer = clone($newanswer); 4708 4709 if (isset($properties->answer_editor[$i])) { 4710 if (is_array($properties->answer_editor[$i])) { 4711 // Multichoice and true/false pages have an HTML editor. 4712 $answer->answer = $properties->answer_editor[$i]['text']; 4713 $answer->answerformat = $properties->answer_editor[$i]['format']; 4714 } else { 4715 // Branch tables, shortanswer and mumerical pages have only a text field. 4716 $answer->answer = $properties->answer_editor[$i]; 4717 $answer->answerformat = FORMAT_MOODLE; 4718 } 4719 } 4720 if (!empty($properties->response_editor[$i]) && is_array($properties->response_editor[$i])) { 4721 $answer->response = $properties->response_editor[$i]['text']; 4722 $answer->responseformat = $properties->response_editor[$i]['format']; 4723 } 4724 4725 if (isset($answer->answer) && $answer->answer != '') { 4726 if (isset($properties->jumpto[$i])) { 4727 $answer->jumpto = $properties->jumpto[$i]; 4728 } 4729 if ($this->lesson->custom && isset($properties->score[$i])) { 4730 $answer->score = $properties->score[$i]; 4731 } 4732 $answer->id = $DB->insert_record("lesson_answers", $answer); 4733 if (isset($properties->response_editor[$i])) { 4734 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer, 4735 $properties->answer_editor[$i], $properties->response_editor[$i]); 4736 } else { 4737 $this->save_answers_files($context, $PAGE->course->maxbytes, $answer, 4738 $properties->answer_editor[$i]); 4739 } 4740 $answers[$answer->id] = new lesson_page_answer($answer); 4741 } 4742 } 4743 4744 $this->answers = $answers; 4745 return $answers; 4746 } 4747 4748 /** 4749 * This method MUST be overridden by all question page types, or page types that 4750 * wish to score a page. 4751 * 4752 * The structure of result should always be the same so it is a good idea when 4753 * overriding this method on a page type to call 4754 * <code> 4755 * $result = parent::check_answer(); 4756 * </code> 4757 * before modifying it as required. 4758 * 4759 * @return stdClass 4760 */ 4761 public function check_answer() { 4762 $result = new stdClass; 4763 $result->answerid = 0; 4764 $result->noanswer = false; 4765 $result->correctanswer = false; 4766 $result->isessayquestion = false; // use this to turn off review button on essay questions 4767 $result->response = ''; 4768 $result->newpageid = 0; // stay on the page 4769 $result->studentanswer = ''; // use this to store student's answer(s) in order to display it on feedback page 4770 $result->studentanswerformat = FORMAT_MOODLE; 4771 $result->userresponse = null; 4772 $result->feedback = ''; 4773 // Store data that was POSTd by a form. This is currently used to perform any logic after the 1st write to the db 4774 // of the attempt. 4775 $result->postdata = false; 4776 $result->nodefaultresponse = false; // Flag for redirecting when default feedback is turned off 4777 $result->inmediatejump = false; // Flag to detect when we should do a jump from the page without further processing. 4778 return $result; 4779 } 4780 4781 /** 4782 * Do any post persistence processing logic of an attempt. E.g. in cases where we need update file urls in an editor 4783 * and we need to have the id of the stored attempt. Should be overridden in each individual child 4784 * pagetype on a as required basis 4785 * 4786 * @param object $attempt The attempt corresponding to the db record 4787 * @param object $result The result from the 'check_answer' method 4788 * @return array False if nothing to be modified, updated $attempt and $result if update required. 4789 */ 4790 public function on_after_write_attempt($attempt, $result) { 4791 return [false, false]; 4792 } 4793 4794 /** 4795 * True if the page uses a custom option 4796 * 4797 * Should be override and set to true if the page uses a custom option. 4798 * 4799 * @return bool 4800 */ 4801 public function has_option() { 4802 return false; 4803 } 4804 4805 /** 4806 * Returns the maximum number of answers for this page given the maximum number 4807 * of answers permitted by the lesson. 4808 * 4809 * @param int $default 4810 * @return int 4811 */ 4812 public function max_answers($default) { 4813 return $default; 4814 } 4815 4816 /** 4817 * Returns the properties of this lesson page as an object 4818 * @return stdClass; 4819 */ 4820 public function properties() { 4821 $properties = clone($this->properties); 4822 if ($this->answers === null) { 4823 $this->get_answers(); 4824 } 4825 if (count($this->answers)>0) { 4826 $count = 0; 4827 $qtype = $properties->qtype; 4828 foreach ($this->answers as $answer) { 4829 $properties->{'answer_editor['.$count.']'} = array('text' => $answer->answer, 'format' => $answer->answerformat); 4830 if ($qtype != LESSON_PAGE_MATCHING) { 4831 $properties->{'response_editor['.$count.']'} = array('text' => $answer->response, 'format' => $answer->responseformat); 4832 } else { 4833 $properties->{'response_editor['.$count.']'} = $answer->response; 4834 } 4835 $properties->{'jumpto['.$count.']'} = $answer->jumpto; 4836 $properties->{'score['.$count.']'} = $answer->score; 4837 $count++; 4838 } 4839 } 4840 return $properties; 4841 } 4842 4843 /** 4844 * Returns an array of options to display when choosing the jumpto for a page/answer 4845 * @static 4846 * @param int $pageid 4847 * @param lesson $lesson 4848 * @return array 4849 */ 4850 public static function get_jumptooptions($pageid, lesson $lesson) { 4851 global $DB; 4852 $jump = array(); 4853 $jump[0] = get_string("thispage", "lesson"); 4854 $jump[LESSON_NEXTPAGE] = get_string("nextpage", "lesson"); 4855 $jump[LESSON_PREVIOUSPAGE] = get_string("previouspage", "lesson"); 4856 $jump[LESSON_EOL] = get_string("endoflesson", "lesson"); 4857 4858 if ($pageid == 0) { 4859 return $jump; 4860 } 4861 4862 $pages = $lesson->load_all_pages(); 4863 if ($pages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_BRANCHTABLE), array(LESSON_PAGE_ENDOFBRANCH, LESSON_PAGE_CLUSTER))) { 4864 $jump[LESSON_UNSEENBRANCHPAGE] = get_string("unseenpageinbranch", "lesson"); 4865 $jump[LESSON_RANDOMPAGE] = get_string("randompageinbranch", "lesson"); 4866 } 4867 if($pages[$pageid]->qtype == LESSON_PAGE_CLUSTER || $lesson->is_sub_page_of_type($pageid, array(LESSON_PAGE_CLUSTER), array(LESSON_PAGE_ENDOFCLUSTER))) { 4868 $jump[LESSON_CLUSTERJUMP] = get_string("clusterjump", "lesson"); 4869 } 4870 if (!optional_param('firstpage', 0, PARAM_INT)) { 4871 $apageid = $DB->get_field("lesson_pages", "id", array("lessonid" => $lesson->id, "prevpageid" => 0)); 4872 while (true) { 4873 if ($apageid) { 4874 $title = $DB->get_field("lesson_pages", "title", array("id" => $apageid)); 4875 $jump[$apageid] = strip_tags(format_string($title,true)); 4876 $apageid = $DB->get_field("lesson_pages", "nextpageid", array("id" => $apageid)); 4877 } else { 4878 // last page reached 4879 break; 4880 } 4881 } 4882 } 4883 return $jump; 4884 } 4885 /** 4886 * Returns the contents field for the page properly formatted and with plugin 4887 * file url's converted 4888 * @return string 4889 */ 4890 public function get_contents() { 4891 global $PAGE; 4892 if (!empty($this->properties->contents)) { 4893 if (!isset($this->properties->contentsformat)) { 4894 $this->properties->contentsformat = FORMAT_HTML; 4895 } 4896 $context = context_module::instance($PAGE->cm->id); 4897 $contents = file_rewrite_pluginfile_urls($this->properties->contents, 'pluginfile.php', $context->id, 'mod_lesson', 4898 'page_contents', $this->properties->id); // Must do this BEFORE format_text()! 4899 return format_text($contents, $this->properties->contentsformat, 4900 array('context' => $context, 'noclean' => true, 4901 'overflowdiv' => true)); // Page edit is marked with XSS, we want all content here. 4902 } else { 4903 return ''; 4904 } 4905 } 4906 4907 /** 4908 * Set to true if this page should display in the menu block 4909 * @return bool 4910 */ 4911 protected function get_displayinmenublock() { 4912 return false; 4913 } 4914 4915 /** 4916 * Get the string that describes the options of this page type 4917 * @return string 4918 */ 4919 public function option_description_string() { 4920 return ''; 4921 } 4922 4923 /** 4924 * Updates a table with the answers for this page 4925 * @param html_table $table 4926 * @return html_table 4927 */ 4928 public function display_answers(html_table $table) { 4929 $answers = $this->get_answers(); 4930 $i = 1; 4931 foreach ($answers as $answer) { 4932 $cells = array(); 4933 $cells[] = '<label>' . get_string('jump', 'lesson') . ' ' . $i . '</label>:'; 4934 $cells[] = $this->get_jump_name($answer->jumpto); 4935 $table->data[] = new html_table_row($cells); 4936 if ($i === 1){ 4937 $table->data[count($table->data)-1]->cells[0]->style = 'width:20%;'; 4938 } 4939 $i++; 4940 } 4941 return $table; 4942 } 4943 4944 /** 4945 * Determines if this page should be grayed out on the management/report screens 4946 * @return int 0 or 1 4947 */ 4948 protected function get_grayout() { 4949 return 0; 4950 } 4951 4952 /** 4953 * Adds stats for this page to the &pagestats object. This should be defined 4954 * for all page types that grade 4955 * @param array $pagestats 4956 * @param int $tries 4957 * @return bool 4958 */ 4959 public function stats(array &$pagestats, $tries) { 4960 return true; 4961 } 4962 4963 /** 4964 * Formats the answers of this page for a report 4965 * 4966 * @param object $answerpage 4967 * @param object $answerdata 4968 * @param object $useranswer 4969 * @param array $pagestats 4970 * @param int $i Count of first level answers 4971 * @param int $n Count of second level answers 4972 * @return object The answer page for this 4973 */ 4974 public function report_answers($answerpage, $answerdata, $useranswer, $pagestats, &$i, &$n) { 4975 $answers = $this->get_answers(); 4976 $formattextdefoptions = new stdClass; 4977 $formattextdefoptions->para = false; //I'll use it widely in this page 4978 foreach ($answers as $answer) { 4979 $data = get_string('jumpsto', 'lesson', $this->get_jump_name($answer->jumpto)); 4980 $answerdata->answers[] = array($data, ""); 4981 $answerpage->answerdata = $answerdata; 4982 } 4983 return $answerpage; 4984 } 4985 4986 /** 4987 * Gets an array of the jumps used by the answers of this page 4988 * 4989 * @return array 4990 */ 4991 public function get_jumps() { 4992 global $DB; 4993 $jumps = array(); 4994 $params = array ("lessonid" => $this->lesson->id, "pageid" => $this->properties->id); 4995 if ($answers = $this->get_answers()) { 4996 foreach ($answers as $answer) { 4997 $jumps[] = $this->get_jump_name($answer->jumpto); 4998 } 4999 } else { 5000 $jumps[] = $this->get_jump_name($this->properties->nextpageid); 5001 } 5002 return $jumps; 5003 } 5004 /** 5005 * Informs whether this page type require manual grading or not 5006 * @return bool 5007 */ 5008 public function requires_manual_grading() { 5009 return false; 5010 } 5011 5012 /** 5013 * A callback method that allows a page to override the next page a user will 5014 * see during when this page is being completed. 5015 * @return false|int 5016 */ 5017 public function override_next_page() { 5018 return false; 5019 } 5020 5021 /** 5022 * This method is used to determine if this page is a valid page 5023 * 5024 * @param array $validpages 5025 * @param array $pageviews 5026 * @return int The next page id to check 5027 */ 5028 public function valid_page_and_view(&$validpages, &$pageviews) { 5029 $validpages[$this->properties->id] = 1; 5030 return $this->properties->nextpageid; 5031 } 5032 5033 /** 5034 * Get files from the page area file. 5035 * 5036 * @param bool $includedirs whether or not include directories 5037 * @param int $updatedsince return files updated since this time 5038 * @return array list of stored_file objects 5039 * @since Moodle 3.2 5040 */ 5041 public function get_files($includedirs = true, $updatedsince = 0) { 5042 $fs = get_file_storage(); 5043 return $fs->get_area_files($this->lesson->context->id, 'mod_lesson', 'page_contents', $this->properties->id, 5044 'itemid, filepath, filename', $includedirs, $updatedsince); 5045 } 5046 5047 /** 5048 * Make updates to the form data if required. 5049 * 5050 * @since Moodle 3.7 5051 * @param stdClass $data The form data to update. 5052 * @return stdClass The updated fom data. 5053 */ 5054 public function update_form_data(stdClass $data) : stdClass { 5055 return $data; 5056 } 5057 } 5058 5059 5060 5061 /** 5062 * Class used to represent an answer to a page 5063 * 5064 * @property int $id The ID of this answer in the database 5065 * @property int $lessonid The ID of the lesson this answer belongs to 5066 * @property int $pageid The ID of the page this answer belongs to 5067 * @property int $jumpto Identifies where the user goes upon completing a page with this answer 5068 * @property int $grade The grade this answer is worth 5069 * @property int $score The score this answer will give 5070 * @property int $flags Used to store options for the answer 5071 * @property int $timecreated A timestamp of when the answer was created 5072 * @property int $timemodified A timestamp of when the answer was modified 5073 * @property string $answer The answer itself 5074 * @property string $response The response the user sees if selecting this answer 5075 * 5076 * @copyright 2009 Sam Hemelryk 5077 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 5078 */ 5079 class lesson_page_answer extends lesson_base { 5080 5081 /** 5082 * Loads an page answer from the DB 5083 * 5084 * @param int $id 5085 * @return lesson_page_answer 5086 */ 5087 public static function load($id) { 5088 global $DB; 5089 $answer = $DB->get_record("lesson_answers", array("id" => $id)); 5090 return new lesson_page_answer($answer); 5091 } 5092 5093 /** 5094 * Given an object of properties and a page created answer(s) and saves them 5095 * in the database. 5096 * 5097 * @param stdClass $properties 5098 * @param lesson_page $page 5099 * @return array 5100 */ 5101 public static function create($properties, lesson_page $page) { 5102 return $page->create_answers($properties); 5103 } 5104 5105 /** 5106 * Get files from the answer area file. 5107 * 5108 * @param bool $includedirs whether or not include directories 5109 * @param int $updatedsince return files updated since this time 5110 * @return array list of stored_file objects 5111 * @since Moodle 3.2 5112 */ 5113 public function get_files($includedirs = true, $updatedsince = 0) { 5114 5115 $lesson = lesson::load($this->properties->lessonid); 5116 $fs = get_file_storage(); 5117 $answerfiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_answers', $this->properties->id, 5118 'itemid, filepath, filename', $includedirs, $updatedsince); 5119 $responsefiles = $fs->get_area_files($lesson->context->id, 'mod_lesson', 'page_responses', $this->properties->id, 5120 'itemid, filepath, filename', $includedirs, $updatedsince); 5121 return array_merge($answerfiles, $responsefiles); 5122 } 5123 5124 } 5125 5126 /** 5127 * A management class for page types 5128 * 5129 * This class is responsible for managing the different pages. A manager object can 5130 * be retrieved by calling the following line of code: 5131 * <code> 5132 * $manager = lesson_page_type_manager::get($lesson); 5133 * </code> 5134 * The first time the page type manager is retrieved the it includes all of the 5135 * different page types located in mod/lesson/pagetypes. 5136 * 5137 * @copyright 2009 Sam Hemelryk 5138 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 5139 */ 5140 class lesson_page_type_manager { 5141 5142 /** 5143 * An array of different page type classes 5144 * @var array 5145 */ 5146 protected $types = array(); 5147 5148 /** 5149 * Retrieves the lesson page type manager object 5150 * 5151 * If the object hasn't yet been created it is created here. 5152 * 5153 * @staticvar lesson_page_type_manager $pagetypemanager 5154 * @param lesson $lesson 5155 * @return lesson_page_type_manager 5156 */ 5157 public static function get(lesson $lesson) { 5158 static $pagetypemanager; 5159 if (!($pagetypemanager instanceof lesson_page_type_manager)) { 5160 $pagetypemanager = new lesson_page_type_manager(); 5161 $pagetypemanager->load_lesson_types($lesson); 5162 } 5163 return $pagetypemanager; 5164 } 5165 5166 /** 5167 * Finds and loads all lesson page types in mod/lesson/pagetypes 5168 * 5169 * @param lesson $lesson 5170 */ 5171 public function load_lesson_types(lesson $lesson) { 5172 global $CFG; 5173 $basedir = $CFG->dirroot.'/mod/lesson/pagetypes/'; 5174 $dir = dir($basedir); 5175 while (false !== ($entry = $dir->read())) { 5176 if (strpos($entry, '.')===0 || !preg_match('#^[a-zA-Z]+\.php#i', $entry)) { 5177 continue; 5178 } 5179 require_once($basedir.$entry); 5180 $class = 'lesson_page_type_'.strtok($entry,'.'); 5181 if (class_exists($class)) { 5182 $pagetype = new $class(new stdClass, $lesson); 5183 $this->types[$pagetype->typeid] = $pagetype; 5184 } 5185 } 5186 5187 } 5188 5189 /** 5190 * Returns an array of strings to describe the loaded page types 5191 * 5192 * @param int $type Can be used to return JUST the string for the requested type 5193 * @return array 5194 */ 5195 public function get_page_type_strings($type=null, $special=true) { 5196 $types = array(); 5197 foreach ($this->types as $pagetype) { 5198 if (($type===null || $pagetype->type===$type) && ($special===true || $pagetype->is_standard())) { 5199 $types[$pagetype->typeid] = $pagetype->typestring; 5200 } 5201 } 5202 return $types; 5203 } 5204 5205 /** 5206 * Returns the basic string used to identify a page type provided with an id 5207 * 5208 * This string can be used to instantiate or identify the page type class. 5209 * If the page type id is unknown then 'unknown' is returned 5210 * 5211 * @param int $id 5212 * @return string 5213 */ 5214 public function get_page_type_idstring($id) { 5215 foreach ($this->types as $pagetype) { 5216 if ((int)$pagetype->typeid === (int)$id) { 5217 return $pagetype->idstring; 5218 } 5219 } 5220 return 'unknown'; 5221 } 5222 5223 /** 5224 * Loads a page for the provided lesson given it's id 5225 * 5226 * This function loads a page from the lesson when given both the lesson it belongs 5227 * to as well as the page's id. 5228 * If the page doesn't exist an error is thrown 5229 * 5230 * @param int $pageid The id of the page to load 5231 * @param lesson $lesson The lesson the page belongs to 5232 * @return lesson_page A class that extends lesson_page 5233 */ 5234 public function load_page($pageid, lesson $lesson) { 5235 global $DB; 5236 if (!($page =$DB->get_record('lesson_pages', array('id'=>$pageid, 'lessonid'=>$lesson->id)))) { 5237 throw new \moodle_exception('cannotfindpages', 'lesson'); 5238 } 5239 $pagetype = get_class($this->types[$page->qtype]); 5240 $page = new $pagetype($page, $lesson); 5241 return $page; 5242 } 5243 5244 /** 5245 * This function detects errors in the ordering between 2 pages and updates the page records. 5246 * 5247 * @param stdClass $page1 Either the first of 2 pages or null if the $page2 param is the first in the list. 5248 * @param stdClass $page1 Either the second of 2 pages or null if the $page1 param is the last in the list. 5249 */ 5250 protected function check_page_order($page1, $page2) { 5251 global $DB; 5252 if (empty($page1)) { 5253 if ($page2->prevpageid != 0) { 5254 debugging("***prevpageid of page " . $page2->id . " set to 0***"); 5255 $page2->prevpageid = 0; 5256 $DB->set_field("lesson_pages", "prevpageid", 0, array("id" => $page2->id)); 5257 } 5258 } else if (empty($page2)) { 5259 if ($page1->nextpageid != 0) { 5260 debugging("***nextpageid of page " . $page1->id . " set to 0***"); 5261 $page1->nextpageid = 0; 5262 $DB->set_field("lesson_pages", "nextpageid", 0, array("id" => $page1->id)); 5263 } 5264 } else { 5265 if ($page1->nextpageid != $page2->id) { 5266 debugging("***nextpageid of page " . $page1->id . " set to " . $page2->id . "***"); 5267 $page1->nextpageid = $page2->id; 5268 $DB->set_field("lesson_pages", "nextpageid", $page2->id, array("id" => $page1->id)); 5269 } 5270 if ($page2->prevpageid != $page1->id) { 5271 debugging("***prevpageid of page " . $page2->id . " set to " . $page1->id . "***"); 5272 $page2->prevpageid = $page1->id; 5273 $DB->set_field("lesson_pages", "prevpageid", $page1->id, array("id" => $page2->id)); 5274 } 5275 } 5276 } 5277 5278 /** 5279 * This function loads ALL pages that belong to the lesson. 5280 * 5281 * @param lesson $lesson 5282 * @return array An array of lesson_page_type_* 5283 */ 5284 public function load_all_pages(lesson $lesson) { 5285 global $DB; 5286 if (!($pages =$DB->get_records('lesson_pages', array('lessonid'=>$lesson->id)))) { 5287 return array(); // Records returned empty. 5288 } 5289 foreach ($pages as $key=>$page) { 5290 $pagetype = get_class($this->types[$page->qtype]); 5291 $pages[$key] = new $pagetype($page, $lesson); 5292 } 5293 5294 $orderedpages = array(); 5295 $lastpageid = 0; 5296 $morepages = true; 5297 while ($morepages) { 5298 $morepages = false; 5299 foreach ($pages as $page) { 5300 if ((int)$page->prevpageid === (int)$lastpageid) { 5301 // Check for errors in page ordering and fix them on the fly. 5302 $prevpage = null; 5303 if ($lastpageid !== 0) { 5304 $prevpage = $orderedpages[$lastpageid]; 5305 } 5306 $this->check_page_order($prevpage, $page); 5307 $morepages = true; 5308 $orderedpages[$page->id] = $page; 5309 unset($pages[$page->id]); 5310 $lastpageid = $page->id; 5311 if ((int)$page->nextpageid===0) { 5312 break 2; 5313 } else { 5314 break 1; 5315 } 5316 } 5317 } 5318 } 5319 5320 // Add remaining pages and fix the nextpageid links for each page. 5321 foreach ($pages as $page) { 5322 // Check for errors in page ordering and fix them on the fly. 5323 $prevpage = null; 5324 if ($lastpageid !== 0) { 5325 $prevpage = $orderedpages[$lastpageid]; 5326 } 5327 $this->check_page_order($prevpage, $page); 5328 $orderedpages[$page->id] = $page; 5329 unset($pages[$page->id]); 5330 $lastpageid = $page->id; 5331 } 5332 5333 if ($lastpageid !== 0) { 5334 $this->check_page_order($orderedpages[$lastpageid], null); 5335 } 5336 5337 return $orderedpages; 5338 } 5339 5340 /** 5341 * Fetches an mform that can be used to create/edit an page 5342 * 5343 * @param int $type The id for the page type 5344 * @param array $arguments Any arguments to pass to the mform 5345 * @return lesson_add_page_form_base 5346 */ 5347 public function get_page_form($type, $arguments) { 5348 $class = 'lesson_add_page_form_'.$this->get_page_type_idstring($type); 5349 if (!class_exists($class) || get_parent_class($class)!=='lesson_add_page_form_base') { 5350 debugging('Lesson page type unknown class requested '.$class, DEBUG_DEVELOPER); 5351 $class = 'lesson_add_page_form_selection'; 5352 } else if ($class === 'lesson_add_page_form_unknown') { 5353 $class = 'lesson_add_page_form_selection'; 5354 } 5355 return new $class(null, $arguments); 5356 } 5357 5358 /** 5359 * Returns an array of links to use as add page links 5360 * @param int $previd The id of the previous page 5361 * @return array 5362 */ 5363 public function get_add_page_type_links($previd) { 5364 global $OUTPUT; 5365 5366 $links = array(); 5367 5368 foreach ($this->types as $key=>$type) { 5369 if ($link = $type->add_page_link($previd)) { 5370 $links[$key] = $link; 5371 } 5372 } 5373 5374 return $links; 5375 } 5376 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body