3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
19 * Standard library of functions and constants for lesson
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
28 /* Do not include any libraries here! */
31 * Given an object containing all the necessary data,
32 * (defined by the form in mod_form.php) this function
33 * will create a new instance and return the id number
34 * of the new instance.
38 * @param object $lesson Lesson post data from the form
41 function lesson_add_instance($data, $mform) {
44 $cmid = $data->coursemodule;
45 $draftitemid = $data->mediafile;
46 $context = context_module::instance($cmid);
48 lesson_process_pre_save($data);
50 unset($data->mediafile);
51 $lessonid = $DB->insert_record("lesson", $data);
52 $data->id = $lessonid;
54 lesson_update_media_file($lessonid, $context, $draftitemid);
56 lesson_process_post_save($data);
58 lesson_grade_item_update($data);
64 * Given an object containing all the necessary data,
65 * (defined by the form in mod_form.php) this function
66 * will update an existing instance with new data.
69 * @param object $lesson Lesson post data from the form
72 function lesson_update_instance($data, $mform) {
75 $data->id = $data->instance;
76 $cmid = $data->coursemodule;
77 $draftitemid = $data->mediafile;
78 $context = context_module::instance($cmid);
80 lesson_process_pre_save($data);
82 unset($data->mediafile);
83 $DB->update_record("lesson", $data);
85 lesson_update_media_file($data->id, $context, $draftitemid);
87 lesson_process_post_save($data);
89 // update grade item definition
90 lesson_grade_item_update($data);
92 // update grades - TODO: do it only when grading style changes
93 lesson_update_grades($data, 0, false);
99 * This function updates the events associated to the lesson.
100 * If $override is non-zero, then it updates only the events
101 * associated with the specified override.
103 * @uses LESSON_MAX_EVENT_LENGTH
104 * @param object $lesson the lesson object.
105 * @param object $override (optional) limit to a specific override
107 function lesson_update_events($lesson, $override = null) {
110 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
111 require_once($CFG->dirroot . '/calendar/lib.php');
113 // Load the old events relating to this lesson.
114 $conds = array('modulename' => 'lesson',
115 'instance' => $lesson->id);
116 if (!empty($override)) {
117 // Only load events for this override.
118 if (isset($override->userid)) {
119 $conds['userid'] = $override->userid;
121 $conds['groupid'] = $override->groupid;
124 $oldevents = $DB->get_records('event', $conds, 'id ASC');
126 // Now make a to-do list of all that needs to be updated.
127 if (empty($override)) {
128 // We are updating the primary settings for the lesson, so we need to add all the overrides.
129 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $lesson->id), 'id ASC');
130 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
131 // list contains the original (non-override) event for the module. If this is not included
132 // the logic below will end up updating the wrong row when we try to reconcile this $overrides
133 // list against the $oldevents list.
134 array_unshift($overrides, new stdClass());
136 // Just do the one override.
137 $overrides = array($override);
140 // Get group override priorities.
141 $grouppriorities = lesson_get_group_override_priorities($lesson->id);
143 foreach ($overrides as $current) {
144 $groupid = isset($current->groupid) ? $current->groupid : 0;
145 $userid = isset($current->userid) ? $current->userid : 0;
146 $available = isset($current->available) ? $current->available : $lesson->available;
147 $deadline = isset($current->deadline) ? $current->deadline : $lesson->deadline;
149 // Only add open/close events for an override if they differ from the lesson default.
150 $addopen = empty($current->id) || !empty($current->available);
151 $addclose = empty($current->id) || !empty($current->deadline);
153 if (!empty($lesson->coursemodule)) {
154 $cmid = $lesson->coursemodule;
156 $cmid = get_coursemodule_from_instance('lesson', $lesson->id, $lesson->course)->id;
159 $event = new stdClass();
160 $event->type = !$deadline ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
161 $event->description = format_module_intro('lesson', $lesson, $cmid);
162 // Events module won't show user events when the courseid is nonzero.
163 $event->courseid = ($userid) ? 0 : $lesson->course;
164 $event->groupid = $groupid;
165 $event->userid = $userid;
166 $event->modulename = 'lesson';
167 $event->instance = $lesson->id;
168 $event->timestart = $available;
169 $event->timeduration = max($deadline - $available, 0);
170 $event->timesort = $available;
171 $event->visible = instance_is_visible('lesson', $lesson);
172 $event->eventtype = LESSON_EVENT_TYPE_OPEN;
173 $event->priority = null;
175 // Determine the event name and priority.
177 // Group override event.
178 $params = new stdClass();
179 $params->lesson = $lesson->name;
180 $params->group = groups_get_group_name($groupid);
181 if ($params->group === false) {
182 // Group doesn't exist, just skip it.
185 $eventname = get_string('overridegroupeventname', 'lesson', $params);
186 // Set group override priority.
187 if ($grouppriorities !== null) {
188 $openpriorities = $grouppriorities['open'];
189 if (isset($openpriorities[$available])) {
190 $event->priority = $openpriorities[$available];
193 } else if ($userid) {
194 // User override event.
195 $params = new stdClass();
196 $params->lesson = $lesson->name;
197 $eventname = get_string('overrideusereventname', 'lesson', $params);
198 // Set user override priority.
199 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
202 $eventname = $lesson->name;
205 if ($addopen or $addclose) {
206 // Separate start and end events.
207 $event->timeduration = 0;
208 if ($available && $addopen) {
209 if ($oldevent = array_shift($oldevents)) {
210 $event->id = $oldevent->id;
214 $event->name = $eventname.' ('.get_string('lessonopens', 'lesson').')';
215 // The method calendar_event::create will reuse a db record if the id field is set.
216 calendar_event::create($event);
218 if ($deadline && $addclose) {
219 if ($oldevent = array_shift($oldevents)) {
220 $event->id = $oldevent->id;
224 $event->type = CALENDAR_EVENT_TYPE_ACTION;
225 $event->name = $eventname.' ('.get_string('lessoncloses', 'lesson').')';
226 $event->timestart = $deadline;
227 $event->timesort = $deadline;
228 $event->eventtype = LESSON_EVENT_TYPE_CLOSE;
229 if ($groupid && $grouppriorities !== null) {
230 $closepriorities = $grouppriorities['close'];
231 if (isset($closepriorities[$deadline])) {
232 $event->priority = $closepriorities[$deadline];
235 calendar_event::create($event);
240 // Delete any leftover events.
241 foreach ($oldevents as $badevent) {
242 $badevent = calendar_event::load($badevent);
248 * Calculates the priorities of timeopen and timeclose values for group overrides for a lesson.
250 * @param int $lessonid The lesson ID.
251 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
253 function lesson_get_group_override_priorities($lessonid) {
256 // Fetch group overrides.
257 $where = 'lessonid = :lessonid AND groupid IS NOT NULL';
258 $params = ['lessonid' => $lessonid];
259 $overrides = $DB->get_records_select('lesson_overrides', $where, $params, '', 'id, groupid, available, deadline');
265 $grouptimeclose = [];
266 foreach ($overrides as $override) {
267 if ($override->available !== null && !in_array($override->available, $grouptimeopen)) {
268 $grouptimeopen[] = $override->available;
270 if ($override->deadline !== null && !in_array($override->deadline, $grouptimeclose)) {
271 $grouptimeclose[] = $override->deadline;
275 // Sort open times in ascending manner. The earlier open time gets higher priority.
276 sort($grouptimeopen);
278 $opengrouppriorities = [];
280 foreach ($grouptimeopen as $timeopen) {
281 $opengrouppriorities[$timeopen] = $openpriority++;
284 // Sort close times in descending manner. The later close time gets higher priority.
285 rsort($grouptimeclose);
287 $closegrouppriorities = [];
289 foreach ($grouptimeclose as $timeclose) {
290 $closegrouppriorities[$timeclose] = $closepriority++;
294 'open' => $opengrouppriorities,
295 'close' => $closegrouppriorities
300 * This standard function will check all instances of this module
301 * and make sure there are up-to-date events created for each of them.
302 * If courseid = 0, then every lesson event in the site is checked, else
303 * only lesson events belonging to the course specified are checked.
304 * This function is used, in its new format, by restore_refresh_events()
306 * @param int $courseid
309 function lesson_refresh_events($courseid = 0) {
312 if ($courseid == 0) {
313 if (!$lessons = $DB->get_records('lesson')) {
317 if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) {
322 foreach ($lessons as $lesson) {
323 lesson_update_events($lesson);
330 * Given an ID of an instance of this module,
331 * this function will permanently delete the instance
332 * and any data that depends on it.
338 function lesson_delete_instance($id) {
340 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
342 $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST);
343 $lesson = new lesson($lesson);
344 return $lesson->delete();
348 * Return a small object with summary information about what a
349 * user has done with a given particular instance of this module
350 * Used for user activity reports.
351 * $return->time = the time they did it
352 * $return->info = a short text description
355 * @param object $course
356 * @param object $user
358 * @param object $lesson
361 function lesson_user_outline($course, $user, $mod, $lesson) {
364 require_once("$CFG->libdir/gradelib.php");
365 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
366 $return = new stdClass();
368 if (empty($grades->items[0]->grades)) {
369 $return->info = get_string("nolessonattempts", "lesson");
371 $grade = reset($grades->items[0]->grades);
372 if (empty($grade->grade)) {
374 // Check to see if it an ungraded / incomplete attempt.
377 WHERE lessonid = :lessonid
379 ORDER BY starttime DESC";
380 $params = array('lessonid' => $lesson->id, 'userid' => $user->id);
382 if ($attempts = $DB->get_records_sql($sql, $params, 0, 1)) {
383 $attempt = reset($attempts);
384 if ($attempt->completed) {
385 $return->info = get_string("completed", "lesson");
387 $return->info = get_string("notyetcompleted", "lesson");
389 $return->time = $attempt->lessontime;
391 $return->info = get_string("nolessonattempts", "lesson");
394 $return->info = get_string("grade") . ': ' . $grade->str_long_grade;
396 // Datesubmitted == time created. dategraded == time modified or time overridden.
397 // If grade was last modified by the user themselves use date graded. Otherwise use date submitted.
398 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
399 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
400 $return->time = $grade->dategraded;
402 $return->time = $grade->datesubmitted;
410 * Print a detailed representation of what a user has done with
411 * a given particular instance of this module, for user activity reports.
414 * @param object $course
415 * @param object $user
417 * @param object $lesson
420 function lesson_user_complete($course, $user, $mod, $lesson) {
421 global $DB, $OUTPUT, $CFG;
423 require_once("$CFG->libdir/gradelib.php");
425 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
427 // Display the grade and feedback.
428 if (empty($grades->items[0]->grades)) {
429 echo $OUTPUT->container(get_string("nolessonattempts", "lesson"));
431 $grade = reset($grades->items[0]->grades);
432 if (empty($grade->grade)) {
433 // Check to see if it an ungraded / incomplete attempt.
436 WHERE lessonid = :lessonid
438 ORDER by starttime desc";
439 $params = array('lessonid' => $lesson->id, 'userid' => $user->id);
441 if ($attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE)) {
442 if ($attempt->completed) {
443 $status = get_string("completed", "lesson");
445 $status = get_string("notyetcompleted", "lesson");
448 $status = get_string("nolessonattempts", "lesson");
451 $status = get_string("grade") . ': ' . $grade->str_long_grade;
454 // Display the grade or lesson status if there isn't one.
455 echo $OUTPUT->container($status);
457 if ($grade->str_feedback) {
458 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
462 // Display the lesson progress.
463 // Attempt, pages viewed, questions answered, correct answers, time.
464 $params = array ("lessonid" => $lesson->id, "userid" => $user->id);
465 $attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
466 $branches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
467 if (!empty($attempts) or !empty($branches)) {
468 echo $OUTPUT->box_start();
469 $table = new html_table();
471 $table->head = array (get_string("attemptheader", "lesson"),
472 get_string("totalpagesviewedheader", "lesson"),
473 get_string("numberofpagesviewedheader", "lesson"),
474 get_string("numberofcorrectanswersheader", "lesson"),
476 $table->width = "100%";
477 $table->align = array ("center", "center", "center", "center", "center");
478 $table->size = array ("*", "*", "*", "*", "*");
479 $table->cellpadding = 2;
480 $table->cellspacing = 0;
487 // Filter question pages (from lesson_attempts).
488 foreach ($attempts as $attempt) {
489 if ($attempt->retry == $retry) {
492 if ($attempt->correct) {
495 $timeseen = $attempt->timeseen;
497 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
501 if ($attempt->correct) {
509 // Filter content pages (from lesson_branch).
510 foreach ($branches as $branch) {
511 if ($branch->retry == $retry) {
514 $timeseen = $branch->timeseen;
516 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
522 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
524 echo html_writer::table($table);
525 echo $OUTPUT->box_end();
532 * Prints lesson summaries on MyMoodle Page
534 * Prints lesson name, due date and attempt information on
535 * lessons that have a deadline that has not already passed
536 * and it is available for taking.
538 * @deprecated since 3.3
539 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
543 * @uses CONTEXT_MODULE
544 * @param array $courses An array of course objects to get lesson instances from
545 * @param array $htmlarray Store overview output array( course ID => 'lesson' => HTML output )
548 function lesson_print_overview($courses, &$htmlarray) {
549 global $USER, $CFG, $DB, $OUTPUT;
551 debugging('The function lesson_print_overview() is now deprecated.', DEBUG_DEVELOPER);
553 if (!$lessons = get_all_instances_in_courses('lesson', $courses)) {
557 // Get all of the current users attempts on all lessons.
558 $params = array($USER->id);
559 $sql = 'SELECT lessonid, userid, count(userid) as attempts
562 GROUP BY lessonid, userid';
563 $allattempts = $DB->get_records_sql($sql, $params);
564 $completedattempts = array();
565 foreach ($allattempts as $myattempt) {
566 $completedattempts[$myattempt->lessonid] = $myattempt->attempts;
569 // Get the current course ID.
570 $listoflessons = array();
571 foreach ($lessons as $lesson) {
572 $listoflessons[] = $lesson->id;
574 // Get the last page viewed by the current user for every lesson in this course.
575 list($insql, $inparams) = $DB->get_in_or_equal($listoflessons, SQL_PARAMS_NAMED);
576 $dbparams = array_merge($inparams, array('userid' => $USER->id));
578 // Get the lesson attempts for the user that have the maximum 'timeseen' value.
579 $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.answerid as nextpageid, p.qtype ";
580 $from = "FROM {lesson_attempts} l
582 SELECT idselect.lessonid, idselect.userid, MAX(idselect.id) AS id
583 FROM {lesson_attempts} idselect
585 SELECT lessonid, userid, MAX(timeseen) AS timeseen
586 FROM {lesson_attempts}
587 WHERE userid = :userid
589 GROUP BY userid, lessonid
591 ON timeselect.timeseen = idselect.timeseen
592 AND timeselect.userid = idselect.userid
593 AND timeselect.lessonid = idselect.lessonid
594 GROUP BY idselect.userid, idselect.lessonid
597 JOIN {lesson_pages} p
598 ON l.pageid = p.id ";
599 $lastattempts = $DB->get_records_sql($select . $from, $dbparams);
601 // Now, get the lesson branches for the user that have the maximum 'timeseen' value.
602 $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.nextpageid, p.qtype ";
603 $from = str_replace('{lesson_attempts}', '{lesson_branch}', $from);
604 $lastbranches = $DB->get_records_sql($select . $from, $dbparams);
606 $lastviewed = array();
607 foreach ($lastattempts as $lastattempt) {
608 $lastviewed[$lastattempt->lessonid] = $lastattempt;
611 // Go through the branch times and record the 'timeseen' value if it doesn't exist
612 // for the lesson, or replace it if it exceeds the current recorded time.
613 foreach ($lastbranches as $lastbranch) {
614 if (!isset($lastviewed[$lastbranch->lessonid])) {
615 $lastviewed[$lastbranch->lessonid] = $lastbranch;
616 } else if ($lastviewed[$lastbranch->lessonid]->timeseen < $lastbranch->timeseen) {
617 $lastviewed[$lastbranch->lessonid] = $lastbranch;
621 // Since we have lessons in this course, now include the constants we need.
622 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
625 foreach ($lessons as $lesson) {
626 if ($lesson->deadline != 0 // The lesson has a deadline
627 and $lesson->deadline >= $now // And it is before the deadline has been met
628 and ($lesson->available == 0 or $lesson->available <= $now)) { // And the lesson is available
631 $class = (!$lesson->visible) ? 'dimmed' : '';
634 $context = context_module::instance($lesson->coursemodule);
637 $url = new moodle_url('/mod/lesson/view.php', array('id' => $lesson->coursemodule));
638 $url = html_writer::link($url, format_string($lesson->name, true, array('context' => $context)), array('class' => $class));
639 $str = $OUTPUT->box(get_string('lessonname', 'lesson', $url), 'name');
642 $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info');
644 // Attempt information.
645 if (has_capability('mod/lesson:manage', $context)) {
646 // This is a teacher, Get the Number of user attempts.
647 $attempts = $DB->count_records('lesson_grades', array('lessonid' => $lesson->id));
648 $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info');
649 $str = $OUTPUT->box($str, 'lesson overview');
651 // This is a student, See if the user has at least started the lesson.
652 if (isset($lastviewed[$lesson->id]->timeseen)) {
653 // See if the user has finished this attempt.
654 if (isset($completedattempts[$lesson->id]) &&
655 ($completedattempts[$lesson->id] == ($lastviewed[$lesson->id]->retry + 1))) {
656 // Are additional attempts allowed?
657 if ($lesson->retake) {
658 // User can retake the lesson.
659 $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info');
660 $str = $OUTPUT->box($str, 'lesson overview');
662 // User has completed the lesson and no retakes are allowed.
667 // The last attempt was not finished or the lesson does not contain questions.
668 // See if the last page viewed was a branchtable.
669 require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php');
670 if ($lastviewed[$lesson->id]->qtype == LESSON_PAGE_BRANCHTABLE) {
671 // See if the next pageid is the end of lesson.
672 if ($lastviewed[$lesson->id]->nextpageid == LESSON_EOL) {
673 // The last page viewed was the End of Lesson.
674 if ($lesson->retake) {
675 // User can retake the lesson.
676 $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info');
677 $str = $OUTPUT->box($str, 'lesson overview');
679 // User has completed the lesson and no retakes are allowed.
684 // The last page viewed was NOT the end of lesson.
685 $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info');
686 $str = $OUTPUT->box($str, 'lesson overview');
690 // Last page was a question page, so the attempt is not completed yet.
691 $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info');
692 $str = $OUTPUT->box($str, 'lesson overview');
697 // User has not yet started this lesson.
698 $str .= $OUTPUT->box(get_string('nolessonattempts', 'lesson'), 'info');
699 $str = $OUTPUT->box($str, 'lesson overview');
703 if (empty($htmlarray[$lesson->course]['lesson'])) {
704 $htmlarray[$lesson->course]['lesson'] = $str;
706 $htmlarray[$lesson->course]['lesson'] .= $str;
714 * Function to be run periodically according to the moodle cron
715 * This function searches for things that need to be done, such
716 * as sending out mail, toggling flags etc ...
720 function lesson_cron () {
727 * Return grade for given user or all users.
731 * @param int $lessonid id of lesson
732 * @param int $userid optional user id, 0 means all users
733 * @return array array of grades, false if none
735 function lesson_get_user_grades($lesson, $userid=0) {
738 $params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id);
740 if (!empty($userid)) {
741 $params["userid"] = $userid;
742 $params["userid2"] = $userid;
743 $user = "AND u.id = :userid";
744 $fuser = "AND uu.id = :userid2";
751 if ($lesson->retake) {
752 if ($lesson->usemaxgrade) {
753 $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade
754 FROM {user} u, {lesson_grades} g
755 WHERE u.id = g.userid AND g.lessonid = :lessonid
759 $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade
760 FROM {user} u, {lesson_grades} g
761 WHERE u.id = g.userid AND g.lessonid = :lessonid
765 unset($params['lessonid2']);
766 unset($params['userid2']);
768 // use only first attempts (with lowest id in lesson_grades table)
769 $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted
770 FROM {user} uu, {lesson_grades} gg
771 WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2
775 $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade
776 FROM {user} u, {lesson_grades} g, ($firstonly) f
777 WHERE u.id = g.userid AND g.lessonid = :lessonid
778 AND g.id = f.firstcompleted AND g.userid=f.userid
782 return $DB->get_records_sql($sql, $params);
786 * Update grades in central gradebook
789 * @param object $lesson
790 * @param int $userid specific user only, 0 means all
791 * @param bool $nullifnone
793 function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
795 require_once($CFG->libdir.'/gradelib.php');
797 if ($lesson->grade == 0 || $lesson->practice) {
798 lesson_grade_item_update($lesson);
800 } else if ($grades = lesson_get_user_grades($lesson, $userid)) {
801 lesson_grade_item_update($lesson, $grades);
803 } else if ($userid and $nullifnone) {
804 $grade = new stdClass();
805 $grade->userid = $userid;
806 $grade->rawgrade = null;
807 lesson_grade_item_update($lesson, $grade);
810 lesson_grade_item_update($lesson);
815 * Create grade item for given lesson
818 * @uses GRADE_TYPE_VALUE
819 * @uses GRADE_TYPE_NONE
820 * @param object $lesson object with extra cmidnumber
821 * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
822 * @return int 0 if ok, error code otherwise
824 function lesson_grade_item_update($lesson, $grades=null) {
826 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
827 require_once($CFG->libdir.'/gradelib.php');
830 if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present
831 $params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber);
833 $params = array('itemname'=>$lesson->name);
836 if (!$lesson->practice and $lesson->grade > 0) {
837 $params['gradetype'] = GRADE_TYPE_VALUE;
838 $params['grademax'] = $lesson->grade;
839 $params['grademin'] = 0;
840 } else if (!$lesson->practice and $lesson->grade < 0) {
841 $params['gradetype'] = GRADE_TYPE_SCALE;
842 $params['scaleid'] = -$lesson->grade;
844 // Make sure current grade fetched correctly from $grades
845 $currentgrade = null;
846 if (!empty($grades)) {
847 if (is_array($grades)) {
848 $currentgrade = reset($grades);
850 $currentgrade = $grades;
854 // When converting a score to a scale, use scale's grade maximum to calculate it.
855 if (!empty($currentgrade) && $currentgrade->rawgrade !== null) {
856 $grade = grade_get_grades($lesson->course, 'mod', 'lesson', $lesson->id, $currentgrade->userid);
857 $params['grademax'] = reset($grade->items)->grademax;
860 $params['gradetype'] = GRADE_TYPE_NONE;
863 if ($grades === 'reset') {
864 $params['reset'] = true;
866 } else if (!empty($grades)) {
867 // Need to calculate raw grade (Note: $grades has many forms)
868 if (is_object($grades)) {
869 $grades = array($grades->userid => $grades);
870 } else if (array_key_exists('userid', $grades)) {
871 $grades = array($grades['userid'] => $grades);
873 foreach ($grades as $key => $grade) {
874 if (!is_array($grade)) {
875 $grades[$key] = $grade = (array) $grade;
877 //check raw grade isnt null otherwise we erroneously insert a grade of 0
878 if ($grade['rawgrade'] !== null) {
879 $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100);
881 //setting rawgrade to null just in case user is deleting a grade
882 $grades[$key]['rawgrade'] = null;
887 return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params);
891 * List the actions that correspond to a view of this module.
892 * This is used by the participation report.
894 * Note: This is not used by new logging system. Event with
895 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
896 * be considered as view action.
900 function lesson_get_view_actions() {
901 return array('view','view all');
905 * List the actions that correspond to a post of this module.
906 * This is used by the participation report.
908 * Note: This is not used by new logging system. Event with
909 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
910 * will be considered as post action.
914 function lesson_get_post_actions() {
915 return array('end','start');
919 * Runs any processes that must run before
920 * a lesson insert/update
923 * @param object $lesson Lesson form data
926 function lesson_process_pre_save(&$lesson) {
929 $lesson->timemodified = time();
931 if (empty($lesson->timelimit)) {
932 $lesson->timelimit = 0;
934 if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) {
935 $lesson->timespent = 0;
937 if (!isset($lesson->completed)) {
938 $lesson->completed = 0;
940 if (empty($lesson->gradebetterthan) or !is_numeric($lesson->gradebetterthan) or $lesson->gradebetterthan < 0) {
941 $lesson->gradebetterthan = 0;
942 } else if ($lesson->gradebetterthan > 100) {
943 $lesson->gradebetterthan = 100;
946 if (empty($lesson->width)) {
947 $lesson->width = 640;
949 if (empty($lesson->height)) {
950 $lesson->height = 480;
952 if (empty($lesson->bgcolor)) {
953 $lesson->bgcolor = '#FFFFFF';
956 // Conditions for dependency
957 $conditions = new stdClass;
958 $conditions->timespent = $lesson->timespent;
959 $conditions->completed = $lesson->completed;
960 $conditions->gradebetterthan = $lesson->gradebetterthan;
961 $lesson->conditions = serialize($conditions);
962 unset($lesson->timespent);
963 unset($lesson->completed);
964 unset($lesson->gradebetterthan);
966 if (empty($lesson->password)) {
967 unset($lesson->password);
972 * Runs any processes that must be run
973 * after a lesson insert/update
976 * @param object $lesson Lesson form data
979 function lesson_process_post_save(&$lesson) {
980 // Update the events relating to this lesson.
981 lesson_update_events($lesson);
986 * Implementation of the function for printing the form elements that control
987 * whether the course reset functionality affects the lesson.
989 * @param $mform form passed by reference
991 function lesson_reset_course_form_definition(&$mform) {
992 $mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson'));
993 $mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts','lesson'));
994 $mform->addElement('advcheckbox', 'reset_lesson_user_overrides',
995 get_string('removealluseroverrides', 'lesson'));
996 $mform->addElement('advcheckbox', 'reset_lesson_group_overrides',
997 get_string('removeallgroupoverrides', 'lesson'));
1001 * Course reset form defaults.
1002 * @param object $course
1005 function lesson_reset_course_form_defaults($course) {
1006 return array('reset_lesson' => 1,
1007 'reset_lesson_group_overrides' => 1,
1008 'reset_lesson_user_overrides' => 1);
1012 * Removes all grades from gradebook
1016 * @param int $courseid
1017 * @param string optional type
1019 function lesson_reset_gradebook($courseid, $type='') {
1022 $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
1023 FROM {lesson} l, {course_modules} cm, {modules} m
1024 WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course";
1025 $params = array ("course" => $courseid);
1026 if ($lessons = $DB->get_records_sql($sql,$params)) {
1027 foreach ($lessons as $lesson) {
1028 lesson_grade_item_update($lesson, 'reset');
1034 * Actual implementation of the reset course functionality, delete all the
1035 * lesson attempts for course $data->courseid.
1039 * @param object $data the data submitted from the reset course.
1040 * @return array status array
1042 function lesson_reset_userdata($data) {
1045 $componentstr = get_string('modulenameplural', 'lesson');
1048 if (!empty($data->reset_lesson)) {
1049 $lessonssql = "SELECT l.id
1051 WHERE l.course=:course";
1053 $params = array ("course" => $data->courseid);
1054 $lessons = $DB->get_records_sql($lessonssql, $params);
1056 // Get rid of attempts files.
1057 $fs = get_file_storage();
1059 foreach ($lessons as $lessonid => $unused) {
1060 if (!$cm = get_coursemodule_from_instance('lesson', $lessonid)) {
1063 $context = context_module::instance($cm->id);
1064 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses');
1068 $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params);
1069 $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params);
1070 $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params);
1071 $DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params);
1073 // remove all grades from gradebook
1074 if (empty($data->reset_gradebook_grades)) {
1075 lesson_reset_gradebook($data->courseid);
1078 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false);
1081 // Remove user overrides.
1082 if (!empty($data->reset_lesson_user_overrides)) {
1083 $DB->delete_records_select('lesson_overrides',
1084 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1086 'component' => $componentstr,
1087 'item' => get_string('useroverridesdeleted', 'lesson'),
1090 // Remove group overrides.
1091 if (!empty($data->reset_lesson_group_overrides)) {
1092 $DB->delete_records_select('lesson_overrides',
1093 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1095 'component' => $componentstr,
1096 'item' => get_string('groupoverridesdeleted', 'lesson'),
1099 /// updating dates - shift may be negative too
1100 if ($data->timeshift) {
1101 $DB->execute("UPDATE {lesson_overrides}
1102 SET available = available + ?
1103 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
1104 AND available <> 0", array($data->timeshift, $data->courseid));
1105 $DB->execute("UPDATE {lesson_overrides}
1106 SET deadline = deadline + ?
1107 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
1108 AND deadline <> 0", array($data->timeshift, $data->courseid));
1110 shift_course_mod_dates('lesson', array('available', 'deadline'), $data->timeshift, $data->courseid);
1111 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
1118 * Returns all other caps used in module
1121 function lesson_get_extra_capabilities() {
1122 return array('moodle/site:accessallgroups');
1126 * @uses FEATURE_GROUPS
1127 * @uses FEATURE_GROUPINGS
1128 * @uses FEATURE_MOD_INTRO
1129 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1130 * @uses FEATURE_GRADE_HAS_GRADE
1131 * @uses FEATURE_GRADE_OUTCOMES
1132 * @param string $feature FEATURE_xx constant for requested feature
1133 * @return mixed True if module supports feature, false if not, null if doesn't know
1135 function lesson_supports($feature) {
1137 case FEATURE_GROUPS:
1139 case FEATURE_GROUPINGS:
1141 case FEATURE_MOD_INTRO:
1143 case FEATURE_COMPLETION_TRACKS_VIEWS:
1145 case FEATURE_GRADE_HAS_GRADE:
1147 case FEATURE_COMPLETION_HAS_RULES:
1149 case FEATURE_GRADE_OUTCOMES:
1151 case FEATURE_BACKUP_MOODLE2:
1153 case FEATURE_SHOW_DESCRIPTION:
1161 * Obtains the automatic completion state for this lesson based on any conditions
1162 * in lesson settings.
1164 * @param object $course Course
1165 * @param object $cm course-module
1166 * @param int $userid User ID
1167 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1168 * @return bool True if completed, false if not, $type if conditions not set.
1170 function lesson_get_completion_state($course, $cm, $userid, $type) {
1173 // Get lesson details.
1174 $lesson = $DB->get_record('lesson', array('id' => $cm->instance), '*',
1177 $result = $type; // Default return value.
1178 // If completion option is enabled, evaluate it and return true/false.
1179 if ($lesson->completionendreached) {
1180 $value = $DB->record_exists('lesson_timer', array(
1181 'lessonid' => $lesson->id, 'userid' => $userid, 'completed' => 1));
1182 if ($type == COMPLETION_AND) {
1183 $result = $result && $value;
1185 $result = $result || $value;
1188 if ($lesson->completiontimespent != 0) {
1189 $duration = $DB->get_field_sql(
1190 "SELECT SUM(lessontime - starttime)
1192 WHERE lessonid = :lessonid
1193 AND userid = :userid",
1194 array('userid' => $userid, 'lessonid' => $lesson->id));
1198 if ($type == COMPLETION_AND) {
1199 $result = $result && ($lesson->completiontimespent < $duration);
1201 $result = $result || ($lesson->completiontimespent < $duration);
1207 * This function extends the settings navigation block for the site.
1209 * It is safe to rely on PAGE here as we will only ever be within the module
1210 * context when this is called
1212 * @param settings_navigation $settings
1213 * @param navigation_node $lessonnode
1215 function lesson_extend_settings_navigation($settings, $lessonnode) {
1218 // We want to add these new nodes after the Edit settings node, and before the
1219 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1220 $keys = $lessonnode->get_children_key_list();
1222 $i = array_search('modedit', $keys);
1223 if ($i === false and array_key_exists(0, $keys)) {
1224 $beforekey = $keys[0];
1225 } else if (array_key_exists($i + 1, $keys)) {
1226 $beforekey = $keys[$i + 1];
1229 if (has_capability('mod/lesson:manageoverrides', $PAGE->cm->context)) {
1230 $url = new moodle_url('/mod/lesson/overrides.php', array('cmid' => $PAGE->cm->id));
1231 $node = navigation_node::create(get_string('groupoverrides', 'lesson'),
1232 new moodle_url($url, array('mode' => 'group')),
1233 navigation_node::TYPE_SETTING, null, 'mod_lesson_groupoverrides');
1234 $lessonnode->add_node($node, $beforekey);
1236 $node = navigation_node::create(get_string('useroverrides', 'lesson'),
1237 new moodle_url($url, array('mode' => 'user')),
1238 navigation_node::TYPE_SETTING, null, 'mod_lesson_useroverrides');
1239 $lessonnode->add_node($node, $beforekey);
1242 if (has_capability('mod/lesson:edit', $PAGE->cm->context)) {
1243 $url = new moodle_url('/mod/lesson/view.php', array('id' => $PAGE->cm->id));
1244 $lessonnode->add(get_string('preview', 'lesson'), $url);
1245 $editnode = $lessonnode->add(get_string('edit', 'lesson'));
1246 $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'collapsed'));
1247 $editnode->add(get_string('collapsed', 'lesson'), $url);
1248 $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'full'));
1249 $editnode->add(get_string('full', 'lesson'), $url);
1252 if (has_capability('mod/lesson:viewreports', $PAGE->cm->context)) {
1253 $reportsnode = $lessonnode->add(get_string('reports', 'lesson'));
1254 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportoverview'));
1255 $reportsnode->add(get_string('overview', 'lesson'), $url);
1256 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportdetail'));
1257 $reportsnode->add(get_string('detailedstats', 'lesson'), $url);
1260 if (has_capability('mod/lesson:grade', $PAGE->cm->context)) {
1261 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm->id));
1262 $lessonnode->add(get_string('manualgrading', 'lesson'), $url);
1268 * Get list of available import or export formats
1270 * Copied and modified from lib/questionlib.php
1272 * @param string $type 'import' if import list, otherwise export list assumed
1273 * @return array sorted list of import/export formats available
1275 function lesson_get_import_export_formats($type) {
1277 $fileformats = core_component::get_plugin_list("qformat");
1279 $fileformatname=array();
1280 foreach ($fileformats as $fileformat=>$fdir) {
1281 $format_file = "$fdir/format.php";
1282 if (file_exists($format_file) ) {
1283 require_once($format_file);
1287 $classname = "qformat_$fileformat";
1288 $format_class = new $classname();
1289 if ($type=='import') {
1290 $provided = $format_class->provide_import();
1292 $provided = $format_class->provide_export();
1295 $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat);
1298 natcasesort($fileformatnames);
1300 return $fileformatnames;
1304 * Serves the lesson attachments. Implements needed access control ;-)
1306 * @package mod_lesson
1308 * @param stdClass $course course object
1309 * @param stdClass $cm course module object
1310 * @param stdClass $context context object
1311 * @param string $filearea file area
1312 * @param array $args extra arguments
1313 * @param bool $forcedownload whether or not force download
1314 * @param array $options additional options affecting the file serving
1315 * @return bool false if file not found, does not return if found - justsend the file
1317 function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1320 if ($context->contextlevel != CONTEXT_MODULE) {
1324 $fileareas = lesson_get_file_areas();
1325 if (!array_key_exists($filearea, $fileareas)) {
1329 if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance))) {
1333 require_course_login($course, true, $cm);
1335 if ($filearea === 'page_contents') {
1336 $pageid = (int)array_shift($args);
1337 if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) {
1340 $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args);
1342 } else if ($filearea === 'page_answers' || $filearea === 'page_responses') {
1343 $itemid = (int)array_shift($args);
1344 if (!$pageanswers = $DB->get_record('lesson_answers', array('id' => $itemid))) {
1347 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1349 } else if ($filearea === 'essay_responses') {
1350 $itemid = (int)array_shift($args);
1351 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $itemid))) {
1354 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1356 } else if ($filearea === 'mediafile') {
1357 if (count($args) > 1) {
1358 // Remove the itemid when it appears to be part of the arguments. If there is only one argument
1359 // then it is surely the file name. The itemid is sometimes used to prevent browser caching.
1362 $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args);
1368 $fs = get_file_storage();
1369 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1373 // finally send the file
1374 send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security!
1378 * Returns an array of file areas
1380 * @package mod_lesson
1382 * @return array a list of available file areas
1384 function lesson_get_file_areas() {
1386 $areas['page_contents'] = get_string('pagecontents', 'mod_lesson');
1387 $areas['mediafile'] = get_string('mediafile', 'mod_lesson');
1388 $areas['page_answers'] = get_string('pageanswers', 'mod_lesson');
1389 $areas['page_responses'] = get_string('pageresponses', 'mod_lesson');
1390 $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson');
1395 * Returns a file_info_stored object for the file being requested here
1397 * @package mod_lesson
1399 * @global stdClass $CFG
1400 * @param file_browse $browser file browser instance
1401 * @param array $areas file areas
1402 * @param stdClass $course course object
1403 * @param stdClass $cm course module object
1404 * @param stdClass $context context object
1405 * @param string $filearea file area
1406 * @param int $itemid item ID
1407 * @param string $filepath file path
1408 * @param string $filename file name
1409 * @return file_info_stored
1411 function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
1414 if (!has_capability('moodle/course:managefiles', $context)) {
1415 // No peaking here for students!
1419 // Mediafile area does not have sub directories, so let's select the default itemid to prevent
1420 // the user from selecting a directory to access the mediafile content.
1421 if ($filearea == 'mediafile' && is_null($itemid)) {
1425 if (is_null($itemid)) {
1426 return new mod_lesson_file_info($browser, $course, $cm, $context, $areas, $filearea);
1429 $fs = get_file_storage();
1430 $filepath = is_null($filepath) ? '/' : $filepath;
1431 $filename = is_null($filename) ? '.' : $filename;
1432 if (!$storedfile = $fs->get_file($context->id, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) {
1436 $itemname = $filearea;
1437 if ($filearea == 'page_contents') {
1438 $itemname = $DB->get_field('lesson_pages', 'title', array('lessonid' => $cm->instance, 'id' => $itemid));
1439 $itemname = format_string($itemname, true, array('context' => $context));
1441 $areas = lesson_get_file_areas();
1442 if (isset($areas[$filearea])) {
1443 $itemname = $areas[$filearea];
1447 $urlbase = $CFG->wwwroot . '/pluginfile.php';
1448 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false);
1453 * Return a list of page types
1454 * @param string $pagetype current page type
1455 * @param stdClass $parentcontext Block's parent context
1456 * @param stdClass $currentcontext Current context of block
1458 function lesson_page_type_list($pagetype, $parentcontext, $currentcontext) {
1459 $module_pagetype = array(
1460 'mod-lesson-*'=>get_string('page-mod-lesson-x', 'lesson'),
1461 'mod-lesson-view'=>get_string('page-mod-lesson-view', 'lesson'),
1462 'mod-lesson-edit'=>get_string('page-mod-lesson-edit', 'lesson'));
1463 return $module_pagetype;
1467 * Update the lesson activity to include any file
1468 * that was uploaded, or if there is none, set the
1469 * mediafile field to blank.
1471 * @param int $lessonid the lesson id
1472 * @param stdClass $context the context
1473 * @param int $draftitemid the draft item
1475 function lesson_update_media_file($lessonid, $context, $draftitemid) {
1478 // Set the filestorage object.
1479 $fs = get_file_storage();
1480 // Save the file if it exists that is currently in the draft area.
1481 file_save_draft_area_files($draftitemid, $context->id, 'mod_lesson', 'mediafile', 0);
1482 // Get the file if it exists.
1483 $files = $fs->get_area_files($context->id, 'mod_lesson', 'mediafile', 0, 'itemid, filepath, filename', false);
1484 // Check that there is a file to process.
1485 if (count($files) == 1) {
1486 // Get the first (and only) file.
1487 $file = reset($files);
1488 // Set the mediafile column in the lessons table.
1489 $DB->set_field('lesson', 'mediafile', '/' . $file->get_filename(), array('id' => $lessonid));
1491 // Set the mediafile column in the lessons table.
1492 $DB->set_field('lesson', 'mediafile', '', array('id' => $lessonid));
1497 * Get icon mapping for font-awesome.
1499 function mod_lesson_get_fontawesome_icon_map() {
1501 'mod_lesson:e/copy' => 'fa-clone',
1506 * Check if the module has any update that affects the current user since a given time.
1508 * @param cm_info $cm course module data
1509 * @param int $from the time to check updates from
1510 * @param array $filter if we need to check only specific updates
1511 * @return stdClass an object with the different type of areas indicating if they were updated or not
1514 function lesson_check_updates_since(cm_info $cm, $from, $filter = array()) {
1517 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1519 // Check if there are new pages or answers in the lesson.
1520 $updates->pages = (object) array('updated' => false);
1521 $updates->answers = (object) array('updated' => false);
1522 $select = 'lessonid = ? AND (timecreated > ? OR timemodified > ?)';
1523 $params = array($cm->instance, $from, $from);
1525 $pages = $DB->get_records_select('lesson_pages', $select, $params, '', 'id');
1526 if (!empty($pages)) {
1527 $updates->pages->updated = true;
1528 $updates->pages->itemids = array_keys($pages);
1530 $answers = $DB->get_records_select('lesson_answers', $select, $params, '', 'id');
1531 if (!empty($answers)) {
1532 $updates->answers->updated = true;
1533 $updates->answers->itemids = array_keys($answers);
1536 // Check for new question attempts, grades, pages viewed and timers.
1537 $updates->questionattempts = (object) array('updated' => false);
1538 $updates->grades = (object) array('updated' => false);
1539 $updates->pagesviewed = (object) array('updated' => false);
1540 $updates->timers = (object) array('updated' => false);
1542 $select = 'lessonid = ? AND userid = ? AND timeseen > ?';
1543 $params = array($cm->instance, $USER->id, $from);
1545 $questionattempts = $DB->get_records_select('lesson_attempts', $select, $params, '', 'id');
1546 if (!empty($questionattempts)) {
1547 $updates->questionattempts->updated = true;
1548 $updates->questionattempts->itemids = array_keys($questionattempts);
1550 $pagesviewed = $DB->get_records_select('lesson_branch', $select, $params, '', 'id');
1551 if (!empty($pagesviewed)) {
1552 $updates->pagesviewed->updated = true;
1553 $updates->pagesviewed->itemids = array_keys($pagesviewed);
1556 $select = 'lessonid = ? AND userid = ? AND completed > ?';
1557 $grades = $DB->get_records_select('lesson_grades', $select, $params, '', 'id');
1558 if (!empty($grades)) {
1559 $updates->grades->updated = true;
1560 $updates->grades->itemids = array_keys($grades);
1563 $select = 'lessonid = ? AND userid = ? AND (starttime > ? OR lessontime > ? OR timemodifiedoffline > ?)';
1564 $params = array($cm->instance, $USER->id, $from, $from, $from);
1565 $timers = $DB->get_records_select('lesson_timer', $select, $params, '', 'id');
1566 if (!empty($timers)) {
1567 $updates->timers->updated = true;
1568 $updates->timers->itemids = array_keys($timers);
1571 // Now, teachers should see other students updates.
1572 if (has_capability('mod/lesson:viewreports', $cm->context)) {
1573 $select = 'lessonid = ? AND timeseen > ?';
1574 $params = array($cm->instance, $from);
1578 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1579 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1580 if (empty($groupusers)) {
1583 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1584 $select .= ' AND userid ' . $insql;
1585 $params = array_merge($params, $inparams);
1588 $updates->userquestionattempts = (object) array('updated' => false);
1589 $updates->usergrades = (object) array('updated' => false);
1590 $updates->userpagesviewed = (object) array('updated' => false);
1591 $updates->usertimers = (object) array('updated' => false);
1593 $questionattempts = $DB->get_records_select('lesson_attempts', $select, $params, '', 'id');
1594 if (!empty($questionattempts)) {
1595 $updates->userquestionattempts->updated = true;
1596 $updates->userquestionattempts->itemids = array_keys($questionattempts);
1598 $pagesviewed = $DB->get_records_select('lesson_branch', $select, $params, '', 'id');
1599 if (!empty($pagesviewed)) {
1600 $updates->userpagesviewed->updated = true;
1601 $updates->userpagesviewed->itemids = array_keys($pagesviewed);
1604 $select = 'lessonid = ? AND completed > ?';
1605 if (!empty($insql)) {
1606 $select .= ' AND userid ' . $insql;
1608 $grades = $DB->get_records_select('lesson_grades', $select, $params, '', 'id');
1609 if (!empty($grades)) {
1610 $updates->usergrades->updated = true;
1611 $updates->usergrades->itemids = array_keys($grades);
1614 $select = 'lessonid = ? AND (starttime > ? OR lessontime > ? OR timemodifiedoffline > ?)';
1615 $params = array($cm->instance, $from, $from, $from);
1616 if (!empty($insql)) {
1617 $select .= ' AND userid ' . $insql;
1618 $params = array_merge($params, $inparams);
1620 $timers = $DB->get_records_select('lesson_timer', $select, $params, '', 'id');
1621 if (!empty($timers)) {
1622 $updates->usertimers->updated = true;
1623 $updates->usertimers->itemids = array_keys($timers);
1630 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1632 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1633 * is not displayed on the block.
1635 * @param calendar_event $event
1636 * @param \core_calendar\action_factory $factory
1637 * @return \core_calendar\local\event\entities\action_interface|null
1639 function mod_lesson_core_calendar_provide_event_action(calendar_event $event,
1640 \core_calendar\action_factory $factory) {
1641 global $DB, $CFG, $USER;
1642 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
1644 $cm = get_fast_modinfo($event->courseid)->instances['lesson'][$event->instance];
1645 $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST));
1647 if ($lesson->count_user_retries($USER->id)) {
1648 // If the user has attempted the lesson then there is no further action for the user.
1653 $lesson->update_effective_access($USER->id);
1655 return $factory->create_instance(
1656 get_string('startlesson', 'lesson'),
1657 new \moodle_url('/mod/lesson/view.php', ['id' => $cm->id]),
1659 $lesson->is_accessible()
1664 * Add a get_coursemodule_info function in case any lesson type wants to add 'extra' information
1665 * for the course (see resource).
1667 * Given a course_module object, this function returns any "extra" information that may be needed
1668 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1670 * @param stdClass $coursemodule The coursemodule object (record).
1671 * @return cached_cm_info An object on information that the courses
1672 * will know about (most noticeably, an icon).
1674 function lesson_get_coursemodule_info($coursemodule) {
1677 $dbparams = ['id' => $coursemodule->instance];
1678 $fields = 'id, name, intro, introformat, completionendreached, completiontimespent';
1679 if (!$lesson = $DB->get_record('lesson', $dbparams, $fields)) {
1683 $result = new cached_cm_info();
1684 $result->name = $lesson->name;
1686 if ($coursemodule->showdescription) {
1687 // Convert intro to html. Do not filter cached version, filters run at display time.
1688 $result->content = format_module_intro('lesson', $lesson, $coursemodule->id, false);
1691 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1692 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1693 $result->customdata['customcompletionrules']['completionendreached'] = $lesson->completionendreached;
1694 $result->customdata['customcompletionrules']['completiontimespent'] = $lesson->completiontimespent;
1701 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1703 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1704 * @return array $descriptions the array of descriptions for the custom rules.
1706 function mod_lesson_get_completion_active_rule_descriptions($cm) {
1707 // Values will be present in cm_info, and we assume these are up to date.
1708 if (empty($cm->customdata['customcompletionrules'])
1709 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1714 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1716 case 'completionendreached':
1720 $descriptions[] = get_string('completionendreached_desc', 'lesson', $val);
1722 case 'completiontimespent':
1726 $descriptions[] = get_string('completiontimespentdesc', 'lesson', format_time($val));
1732 return $descriptions;