/mod/lesson/locallib.php
PHP | 5351 lines | 3222 code | 524 blank | 1605 comment | 786 complexity | 4c6febf9ff6dd19337963db1e7dd0f45 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- // This file is part of Moodle - http://moodle.org/
- //
- // Moodle is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // Moodle is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
- /**
- * Local library file for Lesson. These are non-standard functions that are used
- * only by Lesson.
- *
- * @package mod_lesson
- * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or late
- **/
- /** Make sure this isn't being directly accessed */
- defined('MOODLE_INTERNAL') || die();
- /** Include the files that are required by this module */
- require_once($CFG->dirroot.'/course/moodleform_mod.php');
- require_once($CFG->dirroot . '/mod/lesson/lib.php');
- require_once($CFG->libdir . '/filelib.php');
- /** This page */
- define('LESSON_THISPAGE', 0);
- /** Next page -> any page not seen before */
- define("LESSON_UNSEENPAGE", 1);
- /** Next page -> any page not answered correctly */
- define("LESSON_UNANSWEREDPAGE", 2);
- /** Jump to Next Page */
- define("LESSON_NEXTPAGE", -1);
- /** End of Lesson */
- define("LESSON_EOL", -9);
- /** Jump to an unseen page within a branch and end of branch or end of lesson */
- define("LESSON_UNSEENBRANCHPAGE", -50);
- /** Jump to Previous Page */
- define("LESSON_PREVIOUSPAGE", -40);
- /** Jump to a random page within a branch and end of branch or end of lesson */
- define("LESSON_RANDOMPAGE", -60);
- /** Jump to a random Branch */
- define("LESSON_RANDOMBRANCH", -70);
- /** Cluster Jump */
- define("LESSON_CLUSTERJUMP", -80);
- /** Undefined */
- define("LESSON_UNDEFINED", -99);
- /** LESSON_MAX_EVENT_LENGTH = 432000 ; 5 days maximum */
- define("LESSON_MAX_EVENT_LENGTH", "432000");
- /** Answer format is HTML */
- define("LESSON_ANSWER_HTML", "HTML");
- /** Placeholder answer for all other answers. */
- define("LESSON_OTHER_ANSWERS", "@#wronganswer#@");
- //////////////////////////////////////////////////////////////////////////////////////
- /// Any other lesson functions go here. Each of them must have a name that
- /// starts with lesson_
- /**
- * Checks to see if a LESSON_CLUSTERJUMP or
- * a LESSON_UNSEENBRANCHPAGE is used in a lesson.
- *
- * This function is only executed when a teacher is
- * checking the navigation for a lesson.
- *
- * @param stdClass $lesson Id of the lesson that is to be checked.
- * @return boolean True or false.
- **/
- function lesson_display_teacher_warning($lesson) {
- global $DB;
- // get all of the lesson answers
- $params = array ("lessonid" => $lesson->id);
- if (!$lessonanswers = $DB->get_records_select("lesson_answers", "lessonid = :lessonid", $params)) {
- // no answers, then not using cluster or unseen
- return false;
- }
- // just check for the first one that fulfills the requirements
- foreach ($lessonanswers as $lessonanswer) {
- if ($lessonanswer->jumpto == LESSON_CLUSTERJUMP || $lessonanswer->jumpto == LESSON_UNSEENBRANCHPAGE) {
- return true;
- }
- }
- // if no answers use either of the two jumps
- return false;
- }
- /**
- * Interprets the LESSON_UNSEENBRANCHPAGE jump.
- *
- * will return the pageid of a random unseen page that is within a branch
- *
- * @param lesson $lesson
- * @param int $userid Id of the user.
- * @param int $pageid Id of the page from which we are jumping.
- * @return int Id of the next page.
- **/
- function lesson_unseen_question_jump($lesson, $user, $pageid) {
- global $DB;
- // get the number of retakes
- if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$user))) {
- $retakes = 0;
- }
- // get all the lesson_attempts aka what the user has seen
- if ($viewedpages = $DB->get_records("lesson_attempts", array("lessonid"=>$lesson->id, "userid"=>$user, "retry"=>$retakes), "timeseen DESC")) {
- foreach($viewedpages as $viewed) {
- $seenpages[] = $viewed->pageid;
- }
- } else {
- $seenpages = array();
- }
- // get the lesson pages
- $lessonpages = $lesson->load_all_pages();
- if ($pageid == LESSON_UNSEENBRANCHPAGE) { // this only happens when a student leaves in the middle of an unseen question within a branch series
- $pageid = $seenpages[0]; // just change the pageid to the last page viewed inside the branch table
- }
- // go up the pages till branch table
- while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
- if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
- break;
- }
- $pageid = $lessonpages[$pageid]->prevpageid;
- }
- $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
- // this foreach loop stores all the pages that are within the branch table but are not in the $seenpages array
- $unseen = array();
- foreach($pagesinbranch as $page) {
- if (!in_array($page->id, $seenpages)) {
- $unseen[] = $page->id;
- }
- }
- if(count($unseen) == 0) {
- if(isset($pagesinbranch)) {
- $temp = end($pagesinbranch);
- $nextpage = $temp->nextpageid; // they have seen all the pages in the branch, so go to EOB/next branch table/EOL
- } else {
- // there are no pages inside the branch, so return the next page
- $nextpage = $lessonpages[$pageid]->nextpageid;
- }
- if ($nextpage == 0) {
- return LESSON_EOL;
- } else {
- return $nextpage;
- }
- } else {
- return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
- }
- }
- /**
- * Handles the unseen branch table jump.
- *
- * @param lesson $lesson
- * @param int $userid User id.
- * @return int Will return the page id of a branch table or end of lesson
- **/
- function lesson_unseen_branch_jump($lesson, $userid) {
- global $DB;
- if (!$retakes = $DB->count_records("lesson_grades", array("lessonid"=>$lesson->id, "userid"=>$userid))) {
- $retakes = 0;
- }
- if (!$seenbranches = $lesson->get_content_pages_viewed($retakes, $userid, 'timeseen DESC')) {
- print_error('cannotfindrecords', 'lesson');
- }
- // get the lesson pages
- $lessonpages = $lesson->load_all_pages();
- // this loads all the viewed branch tables into $seen until it finds the branch table with the flag
- // which is the branch table that starts the unseenbranch function
- $seen = array();
- foreach ($seenbranches as $seenbranch) {
- if (!$seenbranch->flag) {
- $seen[$seenbranch->pageid] = $seenbranch->pageid;
- } else {
- $start = $seenbranch->pageid;
- break;
- }
- }
- // this function searches through the lesson pages to find all the branch tables
- // that follow the flagged branch table
- $pageid = $lessonpages[$start]->nextpageid; // move down from the flagged branch table
- $branchtables = array();
- while ($pageid != 0) { // grab all of the branch table till eol
- if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
- $branchtables[] = $lessonpages[$pageid]->id;
- }
- $pageid = $lessonpages[$pageid]->nextpageid;
- }
- $unseen = array();
- foreach ($branchtables as $branchtable) {
- // load all of the unseen branch tables into unseen
- if (!array_key_exists($branchtable, $seen)) {
- $unseen[] = $branchtable;
- }
- }
- if (count($unseen) > 0) {
- return $unseen[rand(0, count($unseen)-1)]; // returns a random page id for the next page
- } else {
- return LESSON_EOL; // has viewed all of the branch tables
- }
- }
- /**
- * Handles the random jump between a branch table and end of branch or end of lesson (LESSON_RANDOMPAGE).
- *
- * @param lesson $lesson
- * @param int $pageid The id of the page that we are jumping from (?)
- * @return int The pageid of a random page that is within a branch table
- **/
- function lesson_random_question_jump($lesson, $pageid) {
- global $DB;
- // get the lesson pages
- $params = array ("lessonid" => $lesson->id);
- if (!$lessonpages = $DB->get_records_select("lesson_pages", "lessonid = :lessonid", $params)) {
- print_error('cannotfindpages', 'lesson');
- }
- // go up the pages till branch table
- while ($pageid != 0) { // this condition should never be satisfied... only happens if there are no branch tables above this page
- if ($lessonpages[$pageid]->qtype == LESSON_PAGE_BRANCHTABLE) {
- break;
- }
- $pageid = $lessonpages[$pageid]->prevpageid;
- }
- // get the pages within the branch
- $pagesinbranch = $lesson->get_sub_pages_of($pageid, array(LESSON_PAGE_BRANCHTABLE, LESSON_PAGE_ENDOFBRANCH));
- if(count($pagesinbranch) == 0) {
- // there are no pages inside the branch, so return the next page
- return $lessonpages[$pageid]->nextpageid;
- } else {
- return $pagesinbranch[rand(0, count($pagesinbranch)-1)]->id; // returns a random page id for the next page
- }
- }
- /**
- * Calculates a user's grade for a lesson.
- *
- * @param object $lesson The lesson that the user is taking.
- * @param int $retries The attempt number.
- * @param int $userid Id of the user (optional, default current user).
- * @return object { nquestions => number of questions answered
- attempts => number of question attempts
- total => max points possible
- earned => points earned by student
- grade => calculated percentage grade
- nmanual => number of manually graded questions
- manualpoints => point value for manually graded questions }
- */
- function lesson_grade($lesson, $ntries, $userid = 0) {
- global $USER, $DB;
- if (empty($userid)) {
- $userid = $USER->id;
- }
- // Zero out everything
- $ncorrect = 0;
- $nviewed = 0;
- $score = 0;
- $nmanual = 0;
- $manualpoints = 0;
- $thegrade = 0;
- $nquestions = 0;
- $total = 0;
- $earned = 0;
- $params = array ("lessonid" => $lesson->id, "userid" => $userid, "retry" => $ntries);
- if ($useranswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND
- userid = :userid AND retry = :retry", $params, "timeseen")) {
- // group each try with its page
- $attemptset = array();
- foreach ($useranswers as $useranswer) {
- $attemptset[$useranswer->pageid][] = $useranswer;
- }
- if (!empty($lesson->maxattempts)) {
- // Drop all attempts that go beyond max attempts for the lesson.
- foreach ($attemptset as $key => $set) {
- $attemptset[$key] = array_slice($set, 0, $lesson->maxattempts);
- }
- }
- // get only the pages and their answers that the user answered
- list($usql, $parameters) = $DB->get_in_or_equal(array_keys($attemptset));
- array_unshift($parameters, $lesson->id);
- $pages = $DB->get_records_select("lesson_pages", "lessonid = ? AND id $usql", $parameters);
- $answers = $DB->get_records_select("lesson_answers", "lessonid = ? AND pageid $usql", $parameters);
- // Number of pages answered
- $nquestions = count($pages);
- foreach ($attemptset as $attempts) {
- $page = lesson_page::load($pages[end($attempts)->pageid], $lesson);
- if ($lesson->custom) {
- $attempt = end($attempts);
- // If essay question, handle it, otherwise add to score
- if ($page->requires_manual_grading()) {
- $useranswerobj = unserialize($attempt->useranswer);
- if (isset($useranswerobj->score)) {
- $earned += $useranswerobj->score;
- }
- $nmanual++;
- $manualpoints += $answers[$attempt->answerid]->score;
- } else if (!empty($attempt->answerid)) {
- $earned += $page->earned_score($answers, $attempt);
- }
- } else {
- foreach ($attempts as $attempt) {
- $earned += $attempt->correct;
- }
- $attempt = end($attempts); // doesn't matter which one
- // If essay question, increase numbers
- if ($page->requires_manual_grading()) {
- $nmanual++;
- $manualpoints++;
- }
- }
- // Number of times answered
- $nviewed += count($attempts);
- }
- if ($lesson->custom) {
- $bestscores = array();
- // Find the highest possible score per page to get our total
- foreach ($answers as $answer) {
- if(!isset($bestscores[$answer->pageid])) {
- $bestscores[$answer->pageid] = $answer->score;
- } else if ($bestscores[$answer->pageid] < $answer->score) {
- $bestscores[$answer->pageid] = $answer->score;
- }
- }
- $total = array_sum($bestscores);
- } else {
- // Check to make sure the student has answered the minimum questions
- if ($lesson->minquestions and $nquestions < $lesson->minquestions) {
- // Nope, increase number viewed by the amount of unanswered questions
- $total = $nviewed + ($lesson->minquestions - $nquestions);
- } else {
- $total = $nviewed;
- }
- }
- }
- if ($total) { // not zero
- $thegrade = round(100 * $earned / $total, 5);
- }
- // Build the grade information object
- $gradeinfo = new stdClass;
- $gradeinfo->nquestions = $nquestions;
- $gradeinfo->attempts = $nviewed;
- $gradeinfo->total = $total;
- $gradeinfo->earned = $earned;
- $gradeinfo->grade = $thegrade;
- $gradeinfo->nmanual = $nmanual;
- $gradeinfo->manualpoints = $manualpoints;
- return $gradeinfo;
- }
- /**
- * Determines if a user can view the left menu. The determining factor
- * is whether a user has a grade greater than or equal to the lesson setting
- * of displayleftif
- *
- * @param object $lesson Lesson object of the current lesson
- * @return boolean 0 if the user cannot see, or $lesson->displayleft to keep displayleft unchanged
- **/
- function lesson_displayleftif($lesson) {
- global $CFG, $USER, $DB;
- if (!empty($lesson->displayleftif)) {
- // get the current user's max grade for this lesson
- $params = array ("userid" => $USER->id, "lessonid" => $lesson->id);
- if ($maxgrade = $DB->get_record_sql('SELECT userid, MAX(grade) AS maxgrade FROM {lesson_grades} WHERE userid = :userid AND lessonid = :lessonid GROUP BY userid', $params)) {
- if ($maxgrade->maxgrade < $lesson->displayleftif) {
- return 0; // turn off the displayleft
- }
- } else {
- return 0; // no grades
- }
- }
- // if we get to here, keep the original state of displayleft lesson setting
- return $lesson->displayleft;
- }
- /**
- *
- * @param $cm
- * @param $lesson
- * @param $page
- * @return unknown_type
- */
- function lesson_add_fake_blocks($page, $cm, $lesson, $timer = null) {
- $bc = lesson_menu_block_contents($cm->id, $lesson);
- if (!empty($bc)) {
- $regions = $page->blocks->get_regions();
- $firstregion = reset($regions);
- $page->blocks->add_fake_block($bc, $firstregion);
- }
- $bc = lesson_mediafile_block_contents($cm->id, $lesson);
- if (!empty($bc)) {
- $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
- }
- if (!empty($timer)) {
- $bc = lesson_clock_block_contents($cm->id, $lesson, $timer, $page);
- if (!empty($bc)) {
- $page->blocks->add_fake_block($bc, $page->blocks->get_default_region());
- }
- }
- }
- /**
- * If there is a media file associated with this
- * lesson, return a block_contents that displays it.
- *
- * @param int $cmid Course Module ID for this lesson
- * @param object $lesson Full lesson record object
- * @return block_contents
- **/
- function lesson_mediafile_block_contents($cmid, $lesson) {
- global $OUTPUT;
- if (empty($lesson->mediafile)) {
- return null;
- }
- $options = array();
- $options['menubar'] = 0;
- $options['location'] = 0;
- $options['left'] = 5;
- $options['top'] = 5;
- $options['scrollbars'] = 1;
- $options['resizable'] = 1;
- $options['width'] = $lesson->mediawidth;
- $options['height'] = $lesson->mediaheight;
- $link = new moodle_url('/mod/lesson/mediafile.php?id='.$cmid);
- $action = new popup_action('click', $link, 'lessonmediafile', $options);
- $content = $OUTPUT->action_link($link, get_string('mediafilepopup', 'lesson'), $action, array('title'=>get_string('mediafilepopup', 'lesson')));
- $bc = new block_contents();
- $bc->title = get_string('linkedmedia', 'lesson');
- $bc->attributes['class'] = 'mediafile block';
- $bc->content = $content;
- return $bc;
- }
- /**
- * If a timed lesson and not a teacher, then
- * return a block_contents containing the clock.
- *
- * @param int $cmid Course Module ID for this lesson
- * @param object $lesson Full lesson record object
- * @param object $timer Full timer record object
- * @return block_contents
- **/
- function lesson_clock_block_contents($cmid, $lesson, $timer, $page) {
- // Display for timed lessons and for students only
- $context = context_module::instance($cmid);
- if ($lesson->timelimit == 0 || has_capability('mod/lesson:manage', $context)) {
- return null;
- }
- $content = '<div id="lesson-timer">';
- $content .= $lesson->time_remaining($timer->starttime);
- $content .= '</div>';
- $clocksettings = array('starttime' => $timer->starttime, 'servertime' => time(), 'testlength' => $lesson->timelimit);
- $page->requires->data_for_js('clocksettings', $clocksettings, true);
- $page->requires->strings_for_js(array('timeisup'), 'lesson');
- $page->requires->js('/mod/lesson/timer.js');
- $page->requires->js_init_call('show_clock');
- $bc = new block_contents();
- $bc->title = get_string('timeremaining', 'lesson');
- $bc->attributes['class'] = 'clock block';
- $bc->content = $content;
- return $bc;
- }
- /**
- * If left menu is turned on, then this will
- * print the menu in a block
- *
- * @param int $cmid Course Module ID for this lesson
- * @param lesson $lesson Full lesson record object
- * @return void
- **/
- function lesson_menu_block_contents($cmid, $lesson) {
- global $CFG, $DB;
- if (!$lesson->displayleft) {
- return null;
- }
- $pages = $lesson->load_all_pages();
- foreach ($pages as $page) {
- if ((int)$page->prevpageid === 0) {
- $pageid = $page->id;
- break;
- }
- }
- $currentpageid = optional_param('pageid', $pageid, PARAM_INT);
- if (!$pageid || !$pages) {
- return null;
- }
- $content = '<a href="#maincontent" class="accesshide">' .
- get_string('skip', 'lesson') .
- "</a>\n<div class=\"menuwrapper\">\n<ul>\n";
- while ($pageid != 0) {
- $page = $pages[$pageid];
- // Only process branch tables with display turned on
- if ($page->displayinmenublock && $page->display) {
- if ($page->id == $currentpageid) {
- $content .= '<li class="selected">'.format_string($page->title,true)."</li>\n";
- } else {
- $content .= "<li class=\"notselected\"><a href=\"$CFG->wwwroot/mod/lesson/view.php?id=$cmid&pageid=$page->id\">".format_string($page->title,true)."</a></li>\n";
- }
- }
- $pageid = $page->nextpageid;
- }
- $content .= "</ul>\n</div>\n";
- $bc = new block_contents();
- $bc->title = get_string('lessonmenu', 'lesson');
- $bc->attributes['class'] = 'menu block';
- $bc->content = $content;
- return $bc;
- }
- /**
- * Adds header buttons to the page for the lesson
- *
- * @param object $cm
- * @param object $context
- * @param bool $extraeditbuttons
- * @param int $lessonpageid
- */
- function lesson_add_header_buttons($cm, $context, $extraeditbuttons=false, $lessonpageid=null) {
- global $CFG, $PAGE, $OUTPUT;
- if (has_capability('mod/lesson:edit', $context) && $extraeditbuttons) {
- if ($lessonpageid === null) {
- print_error('invalidpageid', 'lesson');
- }
- if (!empty($lessonpageid) && $lessonpageid != LESSON_EOL) {
- $url = new moodle_url('/mod/lesson/editpage.php', array(
- 'id' => $cm->id,
- 'pageid' => $lessonpageid,
- 'edit' => 1,
- 'returnto' => $PAGE->url->out_as_local_url(false)
- ));
- $PAGE->set_button($OUTPUT->single_button($url, get_string('editpagecontent', 'lesson')));
- }
- }
- }
- /**
- * This is a function used to detect media types and generate html code.
- *
- * @global object $CFG
- * @global object $PAGE
- * @param object $lesson
- * @param object $context
- * @return string $code the html code of media
- */
- function lesson_get_media_html($lesson, $context) {
- global $CFG, $PAGE, $OUTPUT;
- require_once("$CFG->libdir/resourcelib.php");
- // get the media file link
- if (strpos($lesson->mediafile, '://') !== false) {
- $url = new moodle_url($lesson->mediafile);
- } else {
- // the timemodified is used to prevent caching problems, instead of '/' we should better read from files table and use sortorder
- $url = moodle_url::make_pluginfile_url($context->id, 'mod_lesson', 'mediafile', $lesson->timemodified, '/', ltrim($lesson->mediafile, '/'));
- }
- $title = $lesson->mediafile;
- $clicktoopen = html_writer::link($url, get_string('download'));
- $mimetype = resourcelib_guess_url_mimetype($url);
- $extension = resourcelib_get_extension($url->out(false));
- $mediamanager = core_media_manager::instance($PAGE);
- $embedoptions = array(
- core_media_manager::OPTION_TRUSTED => true,
- core_media_manager::OPTION_BLOCK => true
- );
- // find the correct type and print it out
- if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image
- $code = resourcelib_embed_image($url, $title);
- } else if ($mediamanager->can_embed_url($url, $embedoptions)) {
- // Media (audio/video) file.
- $code = $mediamanager->embed_url($url, $title, 0, 0, $embedoptions);
- } else {
- // anything else - just try object tag enlarged as much as possible
- $code = resourcelib_embed_general($url, $title, $clicktoopen, $mimetype);
- }
- return $code;
- }
- /**
- * Logic to happen when a/some group(s) has/have been deleted in a course.
- *
- * @param int $courseid The course ID.
- * @param int $groupid The group id if it is known
- * @return void
- */
- function lesson_process_group_deleted_in_course($courseid, $groupid = null) {
- global $DB;
- $params = array('courseid' => $courseid);
- if ($groupid) {
- $params['groupid'] = $groupid;
- // We just update the group that was deleted.
- $sql = "SELECT o.id, o.lessonid, o.groupid
- FROM {lesson_overrides} o
- JOIN {lesson} lesson ON lesson.id = o.lessonid
- WHERE lesson.course = :courseid
- AND o.groupid = :groupid";
- } else {
- // No groupid, we update all orphaned group overrides for all lessons in course.
- $sql = "SELECT o.id, o.lessonid, o.groupid
- FROM {lesson_overrides} o
- JOIN {lesson} lesson ON lesson.id = o.lessonid
- LEFT JOIN {groups} grp ON grp.id = o.groupid
- WHERE lesson.course = :courseid
- AND o.groupid IS NOT NULL
- AND grp.id IS NULL";
- }
- $records = $DB->get_records_sql($sql, $params);
- if (!$records) {
- return; // Nothing to do.
- }
- $DB->delete_records_list('lesson_overrides', 'id', array_keys($records));
- $cache = cache::make('mod_lesson', 'overrides');
- foreach ($records as $record) {
- $cache->delete("{$record->lessonid}_g_{$record->groupid}");
- }
- }
- /**
- * Return the overview report table and data.
- *
- * @param lesson $lesson lesson instance
- * @param mixed $currentgroup false if not group used, 0 for all groups, group id (int) to filter by that groups
- * @return mixed false if there is no information otherwise html_table and stdClass with the table and data
- * @since Moodle 3.3
- */
- function lesson_get_overview_report_table_and_data(lesson $lesson, $currentgroup) {
- global $DB, $CFG, $OUTPUT;
- require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php');
- $context = $lesson->context;
- $cm = $lesson->cm;
- // Count the number of branch and question pages in this lesson.
- $branchcount = $DB->count_records('lesson_pages', array('lessonid' => $lesson->id, 'qtype' => LESSON_PAGE_BRANCHTABLE));
- $questioncount = ($DB->count_records('lesson_pages', array('lessonid' => $lesson->id)) - $branchcount);
- // Only load students if there attempts for this lesson.
- $attempts = $DB->record_exists('lesson_attempts', array('lessonid' => $lesson->id));
- $branches = $DB->record_exists('lesson_branch', array('lessonid' => $lesson->id));
- $timer = $DB->record_exists('lesson_timer', array('lessonid' => $lesson->id));
- if ($attempts or $branches or $timer) {
- list($esql, $params) = get_enrolled_sql($context, '', $currentgroup, true);
- list($sort, $sortparams) = users_order_by_sql('u');
- // TODO Does not support custom user profile fields (MDL-70456).
- $userfieldsapi = \core_user\fields::for_identity($context, false)->with_userpic();
- $ufields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
- $extrafields = $userfieldsapi->get_required_fields([\core_user\fields::PURPOSE_IDENTITY]);
- $params['a1lessonid'] = $lesson->id;
- $params['b1lessonid'] = $lesson->id;
- $params['c1lessonid'] = $lesson->id;
- $sql = "SELECT DISTINCT $ufields
- FROM {user} u
- JOIN (
- SELECT userid, lessonid FROM {lesson_attempts} a1
- WHERE a1.lessonid = :a1lessonid
- UNION
- SELECT userid, lessonid FROM {lesson_branch} b1
- WHERE b1.lessonid = :b1lessonid
- UNION
- SELECT userid, lessonid FROM {lesson_timer} c1
- WHERE c1.lessonid = :c1lessonid
- ) a ON u.id = a.userid
- JOIN ($esql) ue ON ue.id = a.userid
- ORDER BY $sort";
- $students = $DB->get_recordset_sql($sql, $params);
- if (!$students->valid()) {
- $students->close();
- return array(false, false);
- }
- } else {
- return array(false, false);
- }
- if (! $grades = $DB->get_records('lesson_grades', array('lessonid' => $lesson->id), 'completed')) {
- $grades = array();
- }
- if (! $times = $DB->get_records('lesson_timer', array('lessonid' => $lesson->id), 'starttime')) {
- $times = array();
- }
- // Build an array for output.
- $studentdata = array();
- $attempts = $DB->get_recordset('lesson_attempts', array('lessonid' => $lesson->id), 'timeseen');
- foreach ($attempts as $attempt) {
- // if the user is not in the array or if the retry number is not in the sub array, add the data for that try.
- if (empty($studentdata[$attempt->userid]) || empty($studentdata[$attempt->userid][$attempt->retry])) {
- // restore/setup defaults
- $n = 0;
- $timestart = 0;
- $timeend = 0;
- $usergrade = null;
- $eol = 0;
- // search for the grade record for this try. if not there, the nulls defined above will be used.
- foreach($grades as $grade) {
- // check to see if the grade matches the correct user
- if ($grade->userid == $attempt->userid) {
- // see if n is = to the retry
- if ($n == $attempt->retry) {
- // get grade info
- $usergrade = round($grade->grade, 2); // round it here so we only have to do it once
- break;
- }
- $n++; // if not equal, then increment n
- }
- }
- $n = 0;
- // search for the time record for this try. if not there, the nulls defined above will be used.
- foreach($times as $time) {
- // check to see if the grade matches the correct user
- if ($time->userid == $attempt->userid) {
- // see if n is = to the retry
- if ($n == $attempt->retry) {
- // get grade info
- $timeend = $time->lessontime;
- $timestart = $time->starttime;
- $eol = $time->completed;
- break;
- }
- $n++; // if not equal, then increment n
- }
- }
- // build up the array.
- // this array represents each student and all of their tries at the lesson
- $studentdata[$attempt->userid][$attempt->retry] = array( "timestart" => $timestart,
- "timeend" => $timeend,
- "grade" => $usergrade,
- "end" => $eol,
- "try" => $attempt->retry,
- "userid" => $attempt->userid);
- }
- }
- $attempts->close();
- $branches = $DB->get_recordset('lesson_branch', array('lessonid' => $lesson->id), 'timeseen');
- foreach ($branches as $branch) {
- // If the user is not in the array or if the retry number is not in the sub array, add the data for that try.
- if (empty($studentdata[$branch->userid]) || empty($studentdata[$branch->userid][$branch->retry])) {
- // Restore/setup defaults.
- $n = 0;
- $timestart = 0;
- $timeend = 0;
- $usergrade = null;
- $eol = 0;
- // Search for the time record for this try. if not there, the nulls defined above will be used.
- foreach ($times as $time) {
- // Check to see if the grade matches the correct user.
- if ($time->userid == $branch->userid) {
- // See if n is = to the retry.
- if ($n == $branch->retry) {
- // Get grade info.
- $timeend = $time->lessontime;
- $timestart = $time->starttime;
- $eol = $time->completed;
- break;
- }
- $n++; // If not equal, then increment n.
- }
- }
- // Build up the array.
- // This array represents each student and all of their tries at the lesson.
- $studentdata[$branch->userid][$branch->retry] = array( "timestart" => $timestart,
- "timeend" => $timeend,
- "grade" => $usergrade,
- "end" => $eol,
- "try" => $branch->retry,
- "userid" => $branch->userid);
- }
- }
- $branches->close();
- // Need the same thing for timed entries that were not completed.
- foreach ($times as $time) {
- $endoflesson = $time->completed;
- // If the time start is the same with another record then we shouldn't be adding another item to this array.
- if (isset($studentdata[$time->userid])) {
- $foundmatch = false;
- $n = 0;
- foreach ($studentdata[$time->userid] as $key => $value) {
- if ($value['timestart'] == $time->starttime) {
- // Don't add this to the array.
- $foundmatch = true;
- break;
- }
- }
- $n = count($studentdata[$time->userid]) + 1;
- if (!$foundmatch) {
- // Add a record.
- $studentdata[$time->userid][] = array(
- "timestart" => $time->starttime,
- "timeend" => $time->lessontime,
- "grade" => null,
- "end" => $endoflesson,
- "try" => $n,
- "userid" => $time->userid
- );
- }
- } else {
- $studentdata[$time->userid][] = array(
- "timestart" => $time->starttime,
- "timeend" => $time->lessontime,
- "grade" => null,
- "end" => $endoflesson,
- "try" => 0,
- "userid" => $time->userid
- );
- }
- }
- // To store all the data to be returned by the function.
- $data = new stdClass();
- // Determine if lesson should have a score.
- if ($branchcount > 0 AND $questioncount == 0) {
- // This lesson only contains content pages and is not graded.
- $data->lessonscored = false;
- } else {
- // This lesson is graded.
- $data->lessonscored = true;
- }
- // set all the stats variables
- $data->numofattempts = 0;
- $data->avescore = 0;
- $data->avetime = 0;
- $data->highscore = null;
- $data->lowscore = null;
- $data->hightime = null;
- $data->lowtime = null;
- $data->students = array();
- $table = new html_table();
- $headers = [get_string('name')];
- foreach ($extrafields as $field) {
- $headers[] = \core_user\fields::get_display_name($field);
- }
- $caneditlesson = has_capability('mod/lesson:edit', $context);
- $attemptsheader = get_string('attempts', 'lesson');
- if ($caneditlesson) {
- $selectall = get_string('selectallattempts', 'lesson');
- $deselectall = get_string('deselectallattempts', 'lesson');
- // Build the select/deselect all control.
- $selectallid = 'selectall-attempts';
- $mastercheckbox = new \core\output\checkbox_toggleall('lesson-attempts', true, [
- 'id' => $selectallid,
- 'name' => $selectallid,
- 'value' => 1,
- 'label' => $selectall,
- 'selectall' => $selectall,
- 'deselectall' => $deselectall,
- 'labelclasses' => 'form-check-label'
- ]);
- $attemptsheader = $OUTPUT->render($mastercheckbox);
- }
- $headers [] = $attemptsheader;
- // Set up the table object.
- if ($data->lessonscored) {
- $headers [] = get_string('highscore', 'lesson');
- }
- $colcount = count($headers);
- $table->head = $headers;
- $table->align = [];
- $table->align = array_pad($table->align, $colcount, 'center');
- $table->align[$colcount - 1] = 'left';
- if ($data->lessonscored) {
- $table->align[$colcount - 2] = 'left';
- }
- $table->attributes['class'] = 'table table-striped';
- // print out the $studentdata array
- // going through each student that has attempted the lesson, so, each student should have something to be displayed
- foreach ($students as $student) {
- // check to see if the student has attempts to print out
- if (array_key_exists($student->id, $studentdata)) {
- // set/reset some variables
- $attempts = array();
- $dataforstudent = new stdClass;
- $dataforstudent->attempts = array();
- // gather the data for each user attempt
- $bestgrade = 0;
- // $tries holds all the tries/retries a student has done
- $tries = $studentdata[$student->id];
- $studentname = fullname($student, true);
- foreach ($tries as $try) {
- $dataforstudent->attempts[] = $try;
- // Start to build up the checkbox and link.
- $attempturlparams = [
- 'id' => $cm->id,
- 'action' => 'reportdetail',
- 'userid' => $try['userid'],
- 'try' => $try['try'],
- ];
- if ($try["grade"] !== null) { // if null then not done yet
- // this is what the link does when the user has completed the try
- $timetotake = $try["timeend"] - $try["timestart"];
- if ($try["grade"] > $bestgrade) {
- $bestgrade = $try["grade"];
- }
- $attemptdata = (object)[
- 'grade' => $try["grade"],
- 'timestart' => userdate($try["timestart"]),
- 'duration' => format_time($timetotake),
- ];
- $attemptlinkcontents = get_string('attemptinfowithgrade', 'lesson', $attemptdata);
- } else {
- if ($try["end"]) {
- // User finished the lesson but has no grade. (Happens when there are only content pages).
- $timetotake = $try["timeend"] - $try["timestart"];
- $attemptdata = (object)[
- 'timestart' => userdate($try["timestart"]),
- 'duration' => format_time($timetotake),
- ];
- $attemptlinkcontents = get_string('attemptinfonograde', 'lesson', $attemptdata);
- } else {
- // This is what the link does/looks like when the user has not completed the attempt.
- if ($try['timestart'] !== 0) {
- // Teacher previews do not track time spent.
- $attemptlinkcontents = get_string("notcompletedwithdate", "lesson", userdate($try["timestart"]));
- } else {
- $attemptlinkcontents = get_string("notcompleted", "lesson");
- }
- $timetotake = null;
- }
- }
- $attempturl = new moodle_url('/mod/lesson/report.php', $attempturlparams);
- $attemptlink = html_writer::link($attempturl, $attemptlinkcontents, ['class' => 'lesson-attempt-link']);
- if ($caneditlesson) {
- $attemptid = 'attempt-' . $try['userid'] . '-' . $try['try'];
- $attemptname = 'attempts[' . $try['userid'] . '][' . $try['try'] . ']';
- $checkbox = new \core\output\checkbox_toggleall('lesson-attempts', false, [
- 'id' => $attemptid,
- 'name' => $attemptname,
- 'label' => $attemptlink
- ]);
- $attemptlink = $OUTPUT->render($checkbox);
- }
- // build up the attempts array
- $attempts[] = $attemptlink;
- // Run these lines for the stats only if the user finnished the lesson.
- if ($try["end"]) {
- // User has completed the lesson.
- $data->numofattempts++;
- $data->avetime += $timetotake;
- if ($timetotake > $data->hightime || $data->hightime == null) {
- $data->hightime = $timetotake;
- }
- if ($timetotake < $data->lowtime || $data->lowtime == null) {
- $data->lowtime = $timetotake;
- }
- if ($try["grade"] !== null) {
- // The lesson was scored.
- $data->avescore += $try["grade"];
- if ($try["grade"] > $data->highscore || $data->highscore === null) {
- $data->highscore = $try["grade"];
- }
- if ($try["grade"] < $data->lowscore || $data->lowscore === null) {
- $data->lowscore = $try["grade"];
- }
- }
- }
- }
- // get line breaks in after each attempt
- $attempts = implode("<br />\n", $attempts);
- $row = [$studentname];
- foreach ($extrafields as $field) {
- $row[] = $student->$field;
- }
- $row[] = $attempts;
- if ($data->lessonscored) {
- // Add the grade if the lesson is graded.
- $row[] = $bestgrade."%";
- }
- $table->data[] = $row;
- // Add the student data.
- $dataforstudent->id = $student->id;
- $dataforstudent->fullname = $studentname;
- $dataforstudent->bestgrade = $bestgrade;
- $data->students[] = $dataforstudent;
- }
- }
- $students->close();
- if ($data->numofattempts > 0) {
- $data->avescore = $data->avescore / $data->numofattempts;
- }
- return array($table, $data);
- }
- /**
- * Return information about one user attempt (including answers)
- * @param lesson $lesson lesson instance
- * @param int $userid the user id
- * @param int $attempt the attempt number
- * @return array the user answers (array) and user data stats (object)
- * @since Moodle 3.3
- */
- function lesson_get_user_detailed_report_data(lesson $lesson, $userid, $attempt) {
- global $DB;
- $context = $lesson->context;
- if (!empty($userid)) {
- // Apply overrides.
- $lesson->update_effective_access($userid);
- }
- $pageid = 0;
- $lessonpages = $lesson->load_all_pages();
- foreach ($lessonpages as $lessonpage) {
- if ($lessonpage->prevpageid == 0) {
- $pageid = $lessonpage->id;
- }
- }
- // now gather the stats into an object
- $firstpageid = $pageid;
- $pagestats = array();
- while ($pageid != 0) { // EOL
- $page = $lessonpages[$pageid];
- $params = array ("lessonid" => $lesson->id, "pageid" => $page->id);
- if ($allanswers = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND pageid = :pageid", $params, "timeseen")) {
- // get them ready for processing
- $orderedanswers = array();
- foreach ($allanswers as $singleanswer) {
- // ordering them like this, will help to find the single attempt record that we want to keep.
- $orderedanswers[$singleanswer->userid][$singleanswer->retry][] = $singleanswer;
- }
- // this is foreach user and for each try for that user, keep one attempt record
- foreach ($orderedanswers as $orderedanswer) {
- foreach($orderedanswer as $tries) {
- $page->stats($pagestats, $tries);
- }
- }
- } else {
- // no one answered yet...
- }
- //unset($orderedanswers); initialized above now
- $pageid = $page->nextpageid;
- }
- $manager = lesson_page_type_manager::get($lesson);
- $qtypes = $manager->get_page_type_strings();
- $answerpages = array();
- $answerpage = "";
- $pageid = $firstpageid;
- // cycle through all the pages
- // foreach page, add to the $answerpages[] array all the data that is needed
- // from the question, the users attempt, and the statistics
- // grayout pages that the user did not answer and Branch, end of branch, cluster
- // and end of cluster pages
- while ($pageid != 0) { // EOL
- $page = $lessonpages[$pageid];
- $answerpage = new stdClass;
- // Keep the original page object.
- $answerpage->page = $page;
- $data ='';
- $answerdata = new stdClass;
- // Set some defaults for the answer data.
- $answerdata->score = null;
- $answerdata->response = null;
- $answerdata->responseformat = FORMAT_PLAIN;
- $answerpage->title = format_string($page->title);
- $options = new stdClass;
- $options->noclean = true;
- $options->overflowdiv = true;
- $options->context = $context;
- $answerpage->contents = format_text($page->contents, $page->contentsformat, $options);
- $answerpage->qtype = $qtypes[$page->qtype].$page->option_description_string();
- $answerpage->grayout = $page->grayout;
- $answerpage->context = $context;
- if (empty($userid)) {
- // there is no userid, so set these vars and display stats.
- $answerpage->grayout = 0;
- $useranswer = null;
- } elseif ($useranswers = $DB->get_records("lesson_attempts",array("lessonid"=>$lesson->id, "userid"=>$userid, "retry"=>$attempt,"pageid"=>$page->id), "timeseen")) {
- // get the user's answer for this page
- // need to find the right one
- $i = 0;
- foreach ($useranswers as $userattempt) {
- $useranswer = $userattempt;
- $i++;
- if ($lesson->maxattempts == $i) {
- break; // reached maxattempts, break out
- }
- }
- } else {
- // user did not answer this page, gray it out and set some nulls
- $answerpage->grayout = 1;
- $useranswer = null;
- }
- $i = 0;
- $n = 0;
- $answerpages[] = $page->report_answers(clone($answerpage), clone($answerdata), $useranswer, $pagestats, $i, $n);
- $pageid = $page->nextpageid;
- }
- $userstats = new stdClass;
- if (!empty($userid)) {
- $params = array("lessonid"=>$lesson->id, "userid"=>$userid);
- $alreadycompleted = true;
- if (!$grades = $DB->get_records_select("lesson_grades", "lessonid = :lessonid and userid = :userid", $params, "completed", "*", $attempt, 1)) {
- $userstats->grade = -1;
- $userstats->completed = -1;
- $alreadycompleted = false;
- } else {
- $userstats->grade = current($grades);
- $userstats->completed = $userstats->grade->completed;
- $userstats->grade = round($userstats->grade->grade, 2);
- }
- if (!$times = $lesson->get_user_timers($userid, 'starttime', '*', $attempt, 1)) {
- $userstats->timetotake = -1;
- $alreadycompleted = false;
- } else {
- $userstats->timetotake = current($times);
- $userstats->timetotake = $userstats->timetotake->lessontime - $userstats->timetotake->starttime;
- }
- if ($alreadycompleted) {
- $userstats->gradeinfo = lesson_grade($lesson, $attempt, $userid);
- }
- }
- return array($answerpages, $userstats);
- }
- /**
- * Return user's deadline for all lessons in a course, hereby taking into account group and user overrides.
- *
- * @param int $courseid the course id.
- * @return object An object with of all lessonsids and close unixdates in this course,
- * taking into account the most lenient overrides, if existing and 0 if no close date is set.
- */
- function lesson_get_user_deadline($courseid) {
- global $DB, $USER;
- // For teacher and manager/admins return lesson's deadline.
- if (has_capability('moodle/course:update', context_course::instance($courseid))) {
- $sql = "SELECT lesson.id, lesson.deadline AS userdeadline
- FROM {lesson} lesson
- WHERE lesson.course = :courseid";
- $results = $DB->get_records_sql($sql, array('courseid' => $courseid));
- return $results;
- }
- $sql = "SELECT a.id,
- COALESCE(v.userclose, v.groupclose, a.deadline, 0) AS userdeadline
- FROM (
- SELECT lesson.id as lessonid,
- MAX(leo.deadline) AS userclose, MAX(qgo.deadline) AS groupclose
- FROM {lesson} lesson
- LEFT JOIN {lesson_overrides} leo on lesson.id = leo.lessonid AND leo.userid = :userid
- LEFT JOIN {groups_members} gm ON gm.userid = :useringroupid
- LEFT JOIN {lesson_overrides} qgo on lesson.id = qgo.lessonid AND qgo.groupid = gm.groupid
- WHERE lesson.course = :courseid
- GROUP BY lesson.id
- ) v
- JOIN {lesson} a ON a.id = v.lessonid";
- $results = $DB->get_records_sql($sql, array('userid' => $USER->id, 'useringroupid' => $USER->id, 'courseid' => $courseid));
- return $results;
- }
- /**
- * Abstract class that page type's MUST inherit from.
- *
- * This is the abstract class that ALL add page type forms must extend.
- * You will notice that all but two of the methods this class contains are final.
- * Essentially the only thing that extending classes can do is extend custom_definition.
- * OR if it has a special requirement on creation it can extend construction_override
- *
- * @abstract
- * @copyright 2009 Sam Hemelryk
- * @license …
Large files files are truncated, but you can click here to view the full file