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 = get_string('lessoneventopens', 'lesson', $eventname);
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 = get_string('lessoneventcloses', 'lesson', $eventname);
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
307 * @param int|stdClass $instance Lesson module instance or ID.
308 * @param int|stdClass $cm Course module object or ID (not used in this module).
311 function lesson_refresh_events($courseid = 0, $instance = null, $cm = null) {
314 // If we have instance information then we can just update the one event instead of updating all events.
315 if (isset($instance)) {
316 if (!is_object($instance)) {
317 $instance = $DB->get_record('lesson', array('id' => $instance), '*', MUST_EXIST);
319 lesson_update_events($instance);
323 if ($courseid == 0) {
324 if (!$lessons = $DB->get_records('lesson')) {
328 if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) {
333 foreach ($lessons as $lesson) {
334 lesson_update_events($lesson);
341 * Given an ID of an instance of this module,
342 * this function will permanently delete the instance
343 * and any data that depends on it.
349 function lesson_delete_instance($id) {
351 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
353 $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST);
354 $lesson = new lesson($lesson);
355 return $lesson->delete();
359 * Return a small object with summary information about what a
360 * user has done with a given particular instance of this module
361 * Used for user activity reports.
362 * $return->time = the time they did it
363 * $return->info = a short text description
366 * @param object $course
367 * @param object $user
369 * @param object $lesson
372 function lesson_user_outline($course, $user, $mod, $lesson) {
375 require_once("$CFG->libdir/gradelib.php");
376 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
377 $return = new stdClass();
379 if (empty($grades->items[0]->grades)) {
380 $return->info = get_string("nolessonattempts", "lesson");
382 $grade = reset($grades->items[0]->grades);
383 if (empty($grade->grade)) {
385 // Check to see if it an ungraded / incomplete attempt.
388 WHERE lessonid = :lessonid
390 ORDER BY starttime DESC";
391 $params = array('lessonid' => $lesson->id, 'userid' => $user->id);
393 if ($attempts = $DB->get_records_sql($sql, $params, 0, 1)) {
394 $attempt = reset($attempts);
395 if ($attempt->completed) {
396 $return->info = get_string("completed", "lesson");
398 $return->info = get_string("notyetcompleted", "lesson");
400 $return->time = $attempt->lessontime;
402 $return->info = get_string("nolessonattempts", "lesson");
405 $return->info = get_string("grade") . ': ' . $grade->str_long_grade;
407 // Datesubmitted == time created. dategraded == time modified or time overridden.
408 // If grade was last modified by the user themselves use date graded. Otherwise use date submitted.
409 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
410 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
411 $return->time = $grade->dategraded;
413 $return->time = $grade->datesubmitted;
421 * Print a detailed representation of what a user has done with
422 * a given particular instance of this module, for user activity reports.
425 * @param object $course
426 * @param object $user
428 * @param object $lesson
431 function lesson_user_complete($course, $user, $mod, $lesson) {
432 global $DB, $OUTPUT, $CFG;
434 require_once("$CFG->libdir/gradelib.php");
436 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
438 // Display the grade and feedback.
439 if (empty($grades->items[0]->grades)) {
440 echo $OUTPUT->container(get_string("nolessonattempts", "lesson"));
442 $grade = reset($grades->items[0]->grades);
443 if (empty($grade->grade)) {
444 // Check to see if it an ungraded / incomplete attempt.
447 WHERE lessonid = :lessonid
449 ORDER by starttime desc";
450 $params = array('lessonid' => $lesson->id, 'userid' => $user->id);
452 if ($attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE)) {
453 if ($attempt->completed) {
454 $status = get_string("completed", "lesson");
456 $status = get_string("notyetcompleted", "lesson");
459 $status = get_string("nolessonattempts", "lesson");
462 $status = get_string("grade") . ': ' . $grade->str_long_grade;
465 // Display the grade or lesson status if there isn't one.
466 echo $OUTPUT->container($status);
468 if ($grade->str_feedback) {
469 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
473 // Display the lesson progress.
474 // Attempt, pages viewed, questions answered, correct answers, time.
475 $params = array ("lessonid" => $lesson->id, "userid" => $user->id);
476 $attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
477 $branches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
478 if (!empty($attempts) or !empty($branches)) {
479 echo $OUTPUT->box_start();
480 $table = new html_table();
482 $table->head = array (get_string("attemptheader", "lesson"),
483 get_string("totalpagesviewedheader", "lesson"),
484 get_string("numberofpagesviewedheader", "lesson"),
485 get_string("numberofcorrectanswersheader", "lesson"),
487 $table->width = "100%";
488 $table->align = array ("center", "center", "center", "center", "center");
489 $table->size = array ("*", "*", "*", "*", "*");
490 $table->cellpadding = 2;
491 $table->cellspacing = 0;
498 // Filter question pages (from lesson_attempts).
499 foreach ($attempts as $attempt) {
500 if ($attempt->retry == $retry) {
503 if ($attempt->correct) {
506 $timeseen = $attempt->timeseen;
508 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
512 if ($attempt->correct) {
520 // Filter content pages (from lesson_branch).
521 foreach ($branches as $branch) {
522 if ($branch->retry == $retry) {
525 $timeseen = $branch->timeseen;
527 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
533 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
535 echo html_writer::table($table);
536 echo $OUTPUT->box_end();
543 * Prints lesson summaries on MyMoodle Page
545 * Prints lesson name, due date and attempt information on
546 * lessons that have a deadline that has not already passed
547 * and it is available for taking.
549 * @deprecated since 3.3
550 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
554 * @uses CONTEXT_MODULE
555 * @param array $courses An array of course objects to get lesson instances from
556 * @param array $htmlarray Store overview output array( course ID => 'lesson' => HTML output )
559 function lesson_print_overview($courses, &$htmlarray) {
560 global $USER, $CFG, $DB, $OUTPUT;
562 debugging('The function lesson_print_overview() is now deprecated.', DEBUG_DEVELOPER);
564 if (!$lessons = get_all_instances_in_courses('lesson', $courses)) {
568 // Get all of the current users attempts on all lessons.
569 $params = array($USER->id);
570 $sql = 'SELECT lessonid, userid, count(userid) as attempts
573 GROUP BY lessonid, userid';
574 $allattempts = $DB->get_records_sql($sql, $params);
575 $completedattempts = array();
576 foreach ($allattempts as $myattempt) {
577 $completedattempts[$myattempt->lessonid] = $myattempt->attempts;
580 // Get the current course ID.
581 $listoflessons = array();
582 foreach ($lessons as $lesson) {
583 $listoflessons[] = $lesson->id;
585 // Get the last page viewed by the current user for every lesson in this course.
586 list($insql, $inparams) = $DB->get_in_or_equal($listoflessons, SQL_PARAMS_NAMED);
587 $dbparams = array_merge($inparams, array('userid' => $USER->id));
589 // Get the lesson attempts for the user that have the maximum 'timeseen' value.
590 $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.answerid as nextpageid, p.qtype ";
591 $from = "FROM {lesson_attempts} l
593 SELECT idselect.lessonid, idselect.userid, MAX(idselect.id) AS id
594 FROM {lesson_attempts} idselect
596 SELECT lessonid, userid, MAX(timeseen) AS timeseen
597 FROM {lesson_attempts}
598 WHERE userid = :userid
600 GROUP BY userid, lessonid
602 ON timeselect.timeseen = idselect.timeseen
603 AND timeselect.userid = idselect.userid
604 AND timeselect.lessonid = idselect.lessonid
605 GROUP BY idselect.userid, idselect.lessonid
608 JOIN {lesson_pages} p
609 ON l.pageid = p.id ";
610 $lastattempts = $DB->get_records_sql($select . $from, $dbparams);
612 // Now, get the lesson branches for the user that have the maximum 'timeseen' value.
613 $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.nextpageid, p.qtype ";
614 $from = str_replace('{lesson_attempts}', '{lesson_branch}', $from);
615 $lastbranches = $DB->get_records_sql($select . $from, $dbparams);
617 $lastviewed = array();
618 foreach ($lastattempts as $lastattempt) {
619 $lastviewed[$lastattempt->lessonid] = $lastattempt;
622 // Go through the branch times and record the 'timeseen' value if it doesn't exist
623 // for the lesson, or replace it if it exceeds the current recorded time.
624 foreach ($lastbranches as $lastbranch) {
625 if (!isset($lastviewed[$lastbranch->lessonid])) {
626 $lastviewed[$lastbranch->lessonid] = $lastbranch;
627 } else if ($lastviewed[$lastbranch->lessonid]->timeseen < $lastbranch->timeseen) {
628 $lastviewed[$lastbranch->lessonid] = $lastbranch;
632 // Since we have lessons in this course, now include the constants we need.
633 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
636 foreach ($lessons as $lesson) {
637 if ($lesson->deadline != 0 // The lesson has a deadline
638 and $lesson->deadline >= $now // And it is before the deadline has been met
639 and ($lesson->available == 0 or $lesson->available <= $now)) { // And the lesson is available
642 $class = (!$lesson->visible) ? 'dimmed' : '';
645 $context = context_module::instance($lesson->coursemodule);
648 $url = new moodle_url('/mod/lesson/view.php', array('id' => $lesson->coursemodule));
649 $url = html_writer::link($url, format_string($lesson->name, true, array('context' => $context)), array('class' => $class));
650 $str = $OUTPUT->box(get_string('lessonname', 'lesson', $url), 'name');
653 $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info');
655 // Attempt information.
656 if (has_capability('mod/lesson:manage', $context)) {
657 // This is a teacher, Get the Number of user attempts.
658 $attempts = $DB->count_records('lesson_grades', array('lessonid' => $lesson->id));
659 $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info');
660 $str = $OUTPUT->box($str, 'lesson overview');
662 // This is a student, See if the user has at least started the lesson.
663 if (isset($lastviewed[$lesson->id]->timeseen)) {
664 // See if the user has finished this attempt.
665 if (isset($completedattempts[$lesson->id]) &&
666 ($completedattempts[$lesson->id] == ($lastviewed[$lesson->id]->retry + 1))) {
667 // Are additional attempts allowed?
668 if ($lesson->retake) {
669 // User can retake the lesson.
670 $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info');
671 $str = $OUTPUT->box($str, 'lesson overview');
673 // User has completed the lesson and no retakes are allowed.
678 // The last attempt was not finished or the lesson does not contain questions.
679 // See if the last page viewed was a branchtable.
680 require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php');
681 if ($lastviewed[$lesson->id]->qtype == LESSON_PAGE_BRANCHTABLE) {
682 // See if the next pageid is the end of lesson.
683 if ($lastviewed[$lesson->id]->nextpageid == LESSON_EOL) {
684 // The last page viewed was the End of Lesson.
685 if ($lesson->retake) {
686 // User can retake the lesson.
687 $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info');
688 $str = $OUTPUT->box($str, 'lesson overview');
690 // User has completed the lesson and no retakes are allowed.
695 // The last page viewed was NOT the end of lesson.
696 $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info');
697 $str = $OUTPUT->box($str, 'lesson overview');
701 // Last page was a question page, so the attempt is not completed yet.
702 $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info');
703 $str = $OUTPUT->box($str, 'lesson overview');
708 // User has not yet started this lesson.
709 $str .= $OUTPUT->box(get_string('nolessonattempts', 'lesson'), 'info');
710 $str = $OUTPUT->box($str, 'lesson overview');
714 if (empty($htmlarray[$lesson->course]['lesson'])) {
715 $htmlarray[$lesson->course]['lesson'] = $str;
717 $htmlarray[$lesson->course]['lesson'] .= $str;
725 * Function to be run periodically according to the moodle cron
726 * This function searches for things that need to be done, such
727 * as sending out mail, toggling flags etc ...
731 function lesson_cron () {
738 * Return grade for given user or all users.
742 * @param int $lessonid id of lesson
743 * @param int $userid optional user id, 0 means all users
744 * @return array array of grades, false if none
746 function lesson_get_user_grades($lesson, $userid=0) {
749 $params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id);
751 if (!empty($userid)) {
752 $params["userid"] = $userid;
753 $params["userid2"] = $userid;
754 $user = "AND u.id = :userid";
755 $fuser = "AND uu.id = :userid2";
762 if ($lesson->retake) {
763 if ($lesson->usemaxgrade) {
764 $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade
765 FROM {user} u, {lesson_grades} g
766 WHERE u.id = g.userid AND g.lessonid = :lessonid
770 $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade
771 FROM {user} u, {lesson_grades} g
772 WHERE u.id = g.userid AND g.lessonid = :lessonid
776 unset($params['lessonid2']);
777 unset($params['userid2']);
779 // use only first attempts (with lowest id in lesson_grades table)
780 $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted
781 FROM {user} uu, {lesson_grades} gg
782 WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2
786 $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade
787 FROM {user} u, {lesson_grades} g, ($firstonly) f
788 WHERE u.id = g.userid AND g.lessonid = :lessonid
789 AND g.id = f.firstcompleted AND g.userid=f.userid
793 return $DB->get_records_sql($sql, $params);
797 * Update grades in central gradebook
800 * @param object $lesson
801 * @param int $userid specific user only, 0 means all
802 * @param bool $nullifnone
804 function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
806 require_once($CFG->libdir.'/gradelib.php');
808 if ($lesson->grade == 0 || $lesson->practice) {
809 lesson_grade_item_update($lesson);
811 } else if ($grades = lesson_get_user_grades($lesson, $userid)) {
812 lesson_grade_item_update($lesson, $grades);
814 } else if ($userid and $nullifnone) {
815 $grade = new stdClass();
816 $grade->userid = $userid;
817 $grade->rawgrade = null;
818 lesson_grade_item_update($lesson, $grade);
821 lesson_grade_item_update($lesson);
826 * Create grade item for given lesson
829 * @uses GRADE_TYPE_VALUE
830 * @uses GRADE_TYPE_NONE
831 * @param object $lesson object with extra cmidnumber
832 * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
833 * @return int 0 if ok, error code otherwise
835 function lesson_grade_item_update($lesson, $grades=null) {
837 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
838 require_once($CFG->libdir.'/gradelib.php');
841 if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present
842 $params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber);
844 $params = array('itemname'=>$lesson->name);
847 if (!$lesson->practice and $lesson->grade > 0) {
848 $params['gradetype'] = GRADE_TYPE_VALUE;
849 $params['grademax'] = $lesson->grade;
850 $params['grademin'] = 0;
851 } else if (!$lesson->practice and $lesson->grade < 0) {
852 $params['gradetype'] = GRADE_TYPE_SCALE;
853 $params['scaleid'] = -$lesson->grade;
855 // Make sure current grade fetched correctly from $grades
856 $currentgrade = null;
857 if (!empty($grades)) {
858 if (is_array($grades)) {
859 $currentgrade = reset($grades);
861 $currentgrade = $grades;
865 // When converting a score to a scale, use scale's grade maximum to calculate it.
866 if (!empty($currentgrade) && $currentgrade->rawgrade !== null) {
867 $grade = grade_get_grades($lesson->course, 'mod', 'lesson', $lesson->id, $currentgrade->userid);
868 $params['grademax'] = reset($grade->items)->grademax;
871 $params['gradetype'] = GRADE_TYPE_NONE;
874 if ($grades === 'reset') {
875 $params['reset'] = true;
877 } else if (!empty($grades)) {
878 // Need to calculate raw grade (Note: $grades has many forms)
879 if (is_object($grades)) {
880 $grades = array($grades->userid => $grades);
881 } else if (array_key_exists('userid', $grades)) {
882 $grades = array($grades['userid'] => $grades);
884 foreach ($grades as $key => $grade) {
885 if (!is_array($grade)) {
886 $grades[$key] = $grade = (array) $grade;
888 //check raw grade isnt null otherwise we erroneously insert a grade of 0
889 if ($grade['rawgrade'] !== null) {
890 $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100);
892 //setting rawgrade to null just in case user is deleting a grade
893 $grades[$key]['rawgrade'] = null;
898 return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params);
902 * List the actions that correspond to a view of this module.
903 * This is used by the participation report.
905 * Note: This is not used by new logging system. Event with
906 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
907 * be considered as view action.
911 function lesson_get_view_actions() {
912 return array('view','view all');
916 * List the actions that correspond to a post of this module.
917 * This is used by the participation report.
919 * Note: This is not used by new logging system. Event with
920 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
921 * will be considered as post action.
925 function lesson_get_post_actions() {
926 return array('end','start');
930 * Runs any processes that must run before
931 * a lesson insert/update
934 * @param object $lesson Lesson form data
937 function lesson_process_pre_save(&$lesson) {
940 $lesson->timemodified = time();
942 if (empty($lesson->timelimit)) {
943 $lesson->timelimit = 0;
945 if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) {
946 $lesson->timespent = 0;
948 if (!isset($lesson->completed)) {
949 $lesson->completed = 0;
951 if (empty($lesson->gradebetterthan) or !is_numeric($lesson->gradebetterthan) or $lesson->gradebetterthan < 0) {
952 $lesson->gradebetterthan = 0;
953 } else if ($lesson->gradebetterthan > 100) {
954 $lesson->gradebetterthan = 100;
957 if (empty($lesson->width)) {
958 $lesson->width = 640;
960 if (empty($lesson->height)) {
961 $lesson->height = 480;
963 if (empty($lesson->bgcolor)) {
964 $lesson->bgcolor = '#FFFFFF';
967 // Conditions for dependency
968 $conditions = new stdClass;
969 $conditions->timespent = $lesson->timespent;
970 $conditions->completed = $lesson->completed;
971 $conditions->gradebetterthan = $lesson->gradebetterthan;
972 $lesson->conditions = serialize($conditions);
973 unset($lesson->timespent);
974 unset($lesson->completed);
975 unset($lesson->gradebetterthan);
977 if (empty($lesson->password)) {
978 unset($lesson->password);
983 * Runs any processes that must be run
984 * after a lesson insert/update
987 * @param object $lesson Lesson form data
990 function lesson_process_post_save(&$lesson) {
991 // Update the events relating to this lesson.
992 lesson_update_events($lesson);
993 $completionexpected = (!empty($lesson->completionexpected)) ? $lesson->completionexpected : null;
994 \core_completion\api::update_completion_date_event($lesson->coursemodule, 'lesson', $lesson, $completionexpected);
999 * Implementation of the function for printing the form elements that control
1000 * whether the course reset functionality affects the lesson.
1002 * @param $mform form passed by reference
1004 function lesson_reset_course_form_definition(&$mform) {
1005 $mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson'));
1006 $mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts','lesson'));
1007 $mform->addElement('advcheckbox', 'reset_lesson_user_overrides',
1008 get_string('removealluseroverrides', 'lesson'));
1009 $mform->addElement('advcheckbox', 'reset_lesson_group_overrides',
1010 get_string('removeallgroupoverrides', 'lesson'));
1014 * Course reset form defaults.
1015 * @param object $course
1018 function lesson_reset_course_form_defaults($course) {
1019 return array('reset_lesson' => 1,
1020 'reset_lesson_group_overrides' => 1,
1021 'reset_lesson_user_overrides' => 1);
1025 * Removes all grades from gradebook
1029 * @param int $courseid
1030 * @param string optional type
1032 function lesson_reset_gradebook($courseid, $type='') {
1035 $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
1036 FROM {lesson} l, {course_modules} cm, {modules} m
1037 WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course";
1038 $params = array ("course" => $courseid);
1039 if ($lessons = $DB->get_records_sql($sql,$params)) {
1040 foreach ($lessons as $lesson) {
1041 lesson_grade_item_update($lesson, 'reset');
1047 * Actual implementation of the reset course functionality, delete all the
1048 * lesson attempts for course $data->courseid.
1052 * @param object $data the data submitted from the reset course.
1053 * @return array status array
1055 function lesson_reset_userdata($data) {
1058 $componentstr = get_string('modulenameplural', 'lesson');
1061 if (!empty($data->reset_lesson)) {
1062 $lessonssql = "SELECT l.id
1064 WHERE l.course=:course";
1066 $params = array ("course" => $data->courseid);
1067 $lessons = $DB->get_records_sql($lessonssql, $params);
1069 // Get rid of attempts files.
1070 $fs = get_file_storage();
1072 foreach ($lessons as $lessonid => $unused) {
1073 if (!$cm = get_coursemodule_from_instance('lesson', $lessonid)) {
1076 $context = context_module::instance($cm->id);
1077 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses');
1081 $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params);
1082 $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params);
1083 $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params);
1084 $DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params);
1086 // remove all grades from gradebook
1087 if (empty($data->reset_gradebook_grades)) {
1088 lesson_reset_gradebook($data->courseid);
1091 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false);
1094 // Remove user overrides.
1095 if (!empty($data->reset_lesson_user_overrides)) {
1096 $DB->delete_records_select('lesson_overrides',
1097 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1099 'component' => $componentstr,
1100 'item' => get_string('useroverridesdeleted', 'lesson'),
1103 // Remove group overrides.
1104 if (!empty($data->reset_lesson_group_overrides)) {
1105 $DB->delete_records_select('lesson_overrides',
1106 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1108 'component' => $componentstr,
1109 'item' => get_string('groupoverridesdeleted', 'lesson'),
1112 /// updating dates - shift may be negative too
1113 if ($data->timeshift) {
1114 $DB->execute("UPDATE {lesson_overrides}
1115 SET available = available + ?
1116 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
1117 AND available <> 0", array($data->timeshift, $data->courseid));
1118 $DB->execute("UPDATE {lesson_overrides}
1119 SET deadline = deadline + ?
1120 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
1121 AND deadline <> 0", array($data->timeshift, $data->courseid));
1123 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1125 shift_course_mod_dates('lesson', array('available', 'deadline'), $data->timeshift, $data->courseid);
1126 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
1133 * Returns all other caps used in module
1136 function lesson_get_extra_capabilities() {
1137 return array('moodle/site:accessallgroups');
1141 * @uses FEATURE_GROUPS
1142 * @uses FEATURE_GROUPINGS
1143 * @uses FEATURE_MOD_INTRO
1144 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1145 * @uses FEATURE_GRADE_HAS_GRADE
1146 * @uses FEATURE_GRADE_OUTCOMES
1147 * @param string $feature FEATURE_xx constant for requested feature
1148 * @return mixed True if module supports feature, false if not, null if doesn't know
1150 function lesson_supports($feature) {
1152 case FEATURE_GROUPS:
1154 case FEATURE_GROUPINGS:
1156 case FEATURE_MOD_INTRO:
1158 case FEATURE_COMPLETION_TRACKS_VIEWS:
1160 case FEATURE_GRADE_HAS_GRADE:
1162 case FEATURE_COMPLETION_HAS_RULES:
1164 case FEATURE_GRADE_OUTCOMES:
1166 case FEATURE_BACKUP_MOODLE2:
1168 case FEATURE_SHOW_DESCRIPTION:
1176 * Obtains the automatic completion state for this lesson based on any conditions
1177 * in lesson settings.
1179 * @param object $course Course
1180 * @param object $cm course-module
1181 * @param int $userid User ID
1182 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1183 * @return bool True if completed, false if not, $type if conditions not set.
1185 function lesson_get_completion_state($course, $cm, $userid, $type) {
1188 // Get lesson details.
1189 $lesson = $DB->get_record('lesson', array('id' => $cm->instance), '*',
1192 $result = $type; // Default return value.
1193 // If completion option is enabled, evaluate it and return true/false.
1194 if ($lesson->completionendreached) {
1195 $value = $DB->record_exists('lesson_timer', array(
1196 'lessonid' => $lesson->id, 'userid' => $userid, 'completed' => 1));
1197 if ($type == COMPLETION_AND) {
1198 $result = $result && $value;
1200 $result = $result || $value;
1203 if ($lesson->completiontimespent != 0) {
1204 $duration = $DB->get_field_sql(
1205 "SELECT SUM(lessontime - starttime)
1207 WHERE lessonid = :lessonid
1208 AND userid = :userid",
1209 array('userid' => $userid, 'lessonid' => $lesson->id));
1213 if ($type == COMPLETION_AND) {
1214 $result = $result && ($lesson->completiontimespent < $duration);
1216 $result = $result || ($lesson->completiontimespent < $duration);
1222 * This function extends the settings navigation block for the site.
1224 * It is safe to rely on PAGE here as we will only ever be within the module
1225 * context when this is called
1227 * @param settings_navigation $settings
1228 * @param navigation_node $lessonnode
1230 function lesson_extend_settings_navigation($settings, $lessonnode) {
1233 // We want to add these new nodes after the Edit settings node, and before the
1234 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1235 $keys = $lessonnode->get_children_key_list();
1237 $i = array_search('modedit', $keys);
1238 if ($i === false and array_key_exists(0, $keys)) {
1239 $beforekey = $keys[0];
1240 } else if (array_key_exists($i + 1, $keys)) {
1241 $beforekey = $keys[$i + 1];
1244 if (has_capability('mod/lesson:manageoverrides', $PAGE->cm->context)) {
1245 $url = new moodle_url('/mod/lesson/overrides.php', array('cmid' => $PAGE->cm->id));
1246 $node = navigation_node::create(get_string('groupoverrides', 'lesson'),
1247 new moodle_url($url, array('mode' => 'group')),
1248 navigation_node::TYPE_SETTING, null, 'mod_lesson_groupoverrides');
1249 $lessonnode->add_node($node, $beforekey);
1251 $node = navigation_node::create(get_string('useroverrides', 'lesson'),
1252 new moodle_url($url, array('mode' => 'user')),
1253 navigation_node::TYPE_SETTING, null, 'mod_lesson_useroverrides');
1254 $lessonnode->add_node($node, $beforekey);
1257 if (has_capability('mod/lesson:edit', $PAGE->cm->context)) {
1258 $url = new moodle_url('/mod/lesson/view.php', array('id' => $PAGE->cm->id));
1259 $lessonnode->add(get_string('preview', 'lesson'), $url);
1260 $editnode = $lessonnode->add(get_string('edit', 'lesson'));
1261 $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'collapsed'));
1262 $editnode->add(get_string('collapsed', 'lesson'), $url);
1263 $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'full'));
1264 $editnode->add(get_string('full', 'lesson'), $url);
1267 if (has_capability('mod/lesson:viewreports', $PAGE->cm->context)) {
1268 $reportsnode = $lessonnode->add(get_string('reports', 'lesson'));
1269 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportoverview'));
1270 $reportsnode->add(get_string('overview', 'lesson'), $url);
1271 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportdetail'));
1272 $reportsnode->add(get_string('detailedstats', 'lesson'), $url);
1275 if (has_capability('mod/lesson:grade', $PAGE->cm->context)) {
1276 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm->id));
1277 $lessonnode->add(get_string('manualgrading', 'lesson'), $url);
1283 * Get list of available import or export formats
1285 * Copied and modified from lib/questionlib.php
1287 * @param string $type 'import' if import list, otherwise export list assumed
1288 * @return array sorted list of import/export formats available
1290 function lesson_get_import_export_formats($type) {
1292 $fileformats = core_component::get_plugin_list("qformat");
1294 $fileformatname=array();
1295 foreach ($fileformats as $fileformat=>$fdir) {
1296 $format_file = "$fdir/format.php";
1297 if (file_exists($format_file) ) {
1298 require_once($format_file);
1302 $classname = "qformat_$fileformat";
1303 $format_class = new $classname();
1304 if ($type=='import') {
1305 $provided = $format_class->provide_import();
1307 $provided = $format_class->provide_export();
1310 $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat);
1313 natcasesort($fileformatnames);
1315 return $fileformatnames;
1319 * Serves the lesson attachments. Implements needed access control ;-)
1321 * @package mod_lesson
1323 * @param stdClass $course course object
1324 * @param stdClass $cm course module object
1325 * @param stdClass $context context object
1326 * @param string $filearea file area
1327 * @param array $args extra arguments
1328 * @param bool $forcedownload whether or not force download
1329 * @param array $options additional options affecting the file serving
1330 * @return bool false if file not found, does not return if found - justsend the file
1332 function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1335 if ($context->contextlevel != CONTEXT_MODULE) {
1339 $fileareas = lesson_get_file_areas();
1340 if (!array_key_exists($filearea, $fileareas)) {
1344 if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance))) {
1348 require_course_login($course, true, $cm);
1350 if ($filearea === 'page_contents') {
1351 $pageid = (int)array_shift($args);
1352 if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) {
1355 $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args);
1357 } else if ($filearea === 'page_answers' || $filearea === 'page_responses') {
1358 $itemid = (int)array_shift($args);
1359 if (!$pageanswers = $DB->get_record('lesson_answers', array('id' => $itemid))) {
1362 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1364 } else if ($filearea === 'essay_responses') {
1365 $itemid = (int)array_shift($args);
1366 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $itemid))) {
1369 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1371 } else if ($filearea === 'mediafile') {
1372 if (count($args) > 1) {
1373 // Remove the itemid when it appears to be part of the arguments. If there is only one argument
1374 // then it is surely the file name. The itemid is sometimes used to prevent browser caching.
1377 $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args);
1383 $fs = get_file_storage();
1384 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1388 // finally send the file
1389 send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security!
1393 * Returns an array of file areas
1395 * @package mod_lesson
1397 * @return array a list of available file areas
1399 function lesson_get_file_areas() {
1401 $areas['page_contents'] = get_string('pagecontents', 'mod_lesson');
1402 $areas['mediafile'] = get_string('mediafile', 'mod_lesson');
1403 $areas['page_answers'] = get_string('pageanswers', 'mod_lesson');
1404 $areas['page_responses'] = get_string('pageresponses', 'mod_lesson');
1405 $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson');
1410 * Returns a file_info_stored object for the file being requested here
1412 * @package mod_lesson
1414 * @global stdClass $CFG
1415 * @param file_browse $browser file browser instance
1416 * @param array $areas file areas
1417 * @param stdClass $course course object
1418 * @param stdClass $cm course module object
1419 * @param stdClass $context context object
1420 * @param string $filearea file area
1421 * @param int $itemid item ID
1422 * @param string $filepath file path
1423 * @param string $filename file name
1424 * @return file_info_stored
1426 function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
1429 if (!has_capability('moodle/course:managefiles', $context)) {
1430 // No peaking here for students!
1434 // Mediafile area does not have sub directories, so let's select the default itemid to prevent
1435 // the user from selecting a directory to access the mediafile content.
1436 if ($filearea == 'mediafile' && is_null($itemid)) {
1440 if (is_null($itemid)) {
1441 return new mod_lesson_file_info($browser, $course, $cm, $context, $areas, $filearea);
1444 $fs = get_file_storage();
1445 $filepath = is_null($filepath) ? '/' : $filepath;
1446 $filename = is_null($filename) ? '.' : $filename;
1447 if (!$storedfile = $fs->get_file($context->id, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) {
1451 $itemname = $filearea;
1452 if ($filearea == 'page_contents') {
1453 $itemname = $DB->get_field('lesson_pages', 'title', array('lessonid' => $cm->instance, 'id' => $itemid));
1454 $itemname = format_string($itemname, true, array('context' => $context));
1456 $areas = lesson_get_file_areas();
1457 if (isset($areas[$filearea])) {
1458 $itemname = $areas[$filearea];
1462 $urlbase = $CFG->wwwroot . '/pluginfile.php';
1463 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false);
1468 * Return a list of page types
1469 * @param string $pagetype current page type
1470 * @param stdClass $parentcontext Block's parent context
1471 * @param stdClass $currentcontext Current context of block
1473 function lesson_page_type_list($pagetype, $parentcontext, $currentcontext) {
1474 $module_pagetype = array(
1475 'mod-lesson-*'=>get_string('page-mod-lesson-x', 'lesson'),
1476 'mod-lesson-view'=>get_string('page-mod-lesson-view', 'lesson'),
1477 'mod-lesson-edit'=>get_string('page-mod-lesson-edit', 'lesson'));
1478 return $module_pagetype;
1482 * Update the lesson activity to include any file
1483 * that was uploaded, or if there is none, set the
1484 * mediafile field to blank.
1486 * @param int $lessonid the lesson id
1487 * @param stdClass $context the context
1488 * @param int $draftitemid the draft item
1490 function lesson_update_media_file($lessonid, $context, $draftitemid) {
1493 // Set the filestorage object.
1494 $fs = get_file_storage();
1495 // Save the file if it exists that is currently in the draft area.
1496 file_save_draft_area_files($draftitemid, $context->id, 'mod_lesson', 'mediafile', 0);
1497 // Get the file if it exists.
1498 $files = $fs->get_area_files($context->id, 'mod_lesson', 'mediafile', 0, 'itemid, filepath, filename', false);
1499 // Check that there is a file to process.
1500 if (count($files) == 1) {
1501 // Get the first (and only) file.
1502 $file = reset($files);
1503 // Set the mediafile column in the lessons table.
1504 $DB->set_field('lesson', 'mediafile', '/' . $file->get_filename(), array('id' => $lessonid));
1506 // Set the mediafile column in the lessons table.
1507 $DB->set_field('lesson', 'mediafile', '', array('id' => $lessonid));
1512 * Get icon mapping for font-awesome.
1514 function mod_lesson_get_fontawesome_icon_map() {
1516 'mod_lesson:e/copy' => 'fa-clone',
1521 * Check if the module has any update that affects the current user since a given time.
1523 * @param cm_info $cm course module data
1524 * @param int $from the time to check updates from
1525 * @param array $filter if we need to check only specific updates
1526 * @return stdClass an object with the different type of areas indicating if they were updated or not
1529 function lesson_check_updates_since(cm_info $cm, $from, $filter = array()) {
1532 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1534 // Check if there are new pages or answers in the lesson.
1535 $updates->pages = (object) array('updated' => false);
1536 $updates->answers = (object) array('updated' => false);
1537 $select = 'lessonid = ? AND (timecreated > ? OR timemodified > ?)';
1538 $params = array($cm->instance, $from, $from);
1540 $pages = $DB->get_records_select('lesson_pages', $select, $params, '', 'id');
1541 if (!empty($pages)) {
1542 $updates->pages->updated = true;
1543 $updates->pages->itemids = array_keys($pages);
1545 $answers = $DB->get_records_select('lesson_answers', $select, $params, '', 'id');
1546 if (!empty($answers)) {
1547 $updates->answers->updated = true;
1548 $updates->answers->itemids = array_keys($answers);
1551 // Check for new question attempts, grades, pages viewed and timers.
1552 $updates->questionattempts = (object) array('updated' => false);
1553 $updates->grades = (object) array('updated' => false);
1554 $updates->pagesviewed = (object) array('updated' => false);
1555 $updates->timers = (object) array('updated' => false);
1557 $select = 'lessonid = ? AND userid = ? AND timeseen > ?';
1558 $params = array($cm->instance, $USER->id, $from);
1560 $questionattempts = $DB->get_records_select('lesson_attempts', $select, $params, '', 'id');
1561 if (!empty($questionattempts)) {
1562 $updates->questionattempts->updated = true;
1563 $updates->questionattempts->itemids = array_keys($questionattempts);
1565 $pagesviewed = $DB->get_records_select('lesson_branch', $select, $params, '', 'id');
1566 if (!empty($pagesviewed)) {
1567 $updates->pagesviewed->updated = true;
1568 $updates->pagesviewed->itemids = array_keys($pagesviewed);
1571 $select = 'lessonid = ? AND userid = ? AND completed > ?';
1572 $grades = $DB->get_records_select('lesson_grades', $select, $params, '', 'id');
1573 if (!empty($grades)) {
1574 $updates->grades->updated = true;
1575 $updates->grades->itemids = array_keys($grades);
1578 $select = 'lessonid = ? AND userid = ? AND (starttime > ? OR lessontime > ? OR timemodifiedoffline > ?)';
1579 $params = array($cm->instance, $USER->id, $from, $from, $from);
1580 $timers = $DB->get_records_select('lesson_timer', $select, $params, '', 'id');
1581 if (!empty($timers)) {
1582 $updates->timers->updated = true;
1583 $updates->timers->itemids = array_keys($timers);
1586 // Now, teachers should see other students updates.
1587 if (has_capability('mod/lesson:viewreports', $cm->context)) {
1588 $select = 'lessonid = ? AND timeseen > ?';
1589 $params = array($cm->instance, $from);
1593 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1594 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1595 if (empty($groupusers)) {
1598 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1599 $select .= ' AND userid ' . $insql;
1600 $params = array_merge($params, $inparams);
1603 $updates->userquestionattempts = (object) array('updated' => false);
1604 $updates->usergrades = (object) array('updated' => false);
1605 $updates->userpagesviewed = (object) array('updated' => false);
1606 $updates->usertimers = (object) array('updated' => false);
1608 $questionattempts = $DB->get_records_select('lesson_attempts', $select, $params, '', 'id');
1609 if (!empty($questionattempts)) {
1610 $updates->userquestionattempts->updated = true;
1611 $updates->userquestionattempts->itemids = array_keys($questionattempts);
1613 $pagesviewed = $DB->get_records_select('lesson_branch', $select, $params, '', 'id');
1614 if (!empty($pagesviewed)) {
1615 $updates->userpagesviewed->updated = true;
1616 $updates->userpagesviewed->itemids = array_keys($pagesviewed);
1619 $select = 'lessonid = ? AND completed > ?';
1620 if (!empty($insql)) {
1621 $select .= ' AND userid ' . $insql;
1623 $grades = $DB->get_records_select('lesson_grades', $select, $params, '', 'id');
1624 if (!empty($grades)) {
1625 $updates->usergrades->updated = true;
1626 $updates->usergrades->itemids = array_keys($grades);
1629 $select = 'lessonid = ? AND (starttime > ? OR lessontime > ? OR timemodifiedoffline > ?)';
1630 $params = array($cm->instance, $from, $from, $from);
1631 if (!empty($insql)) {
1632 $select .= ' AND userid ' . $insql;
1633 $params = array_merge($params, $inparams);
1635 $timers = $DB->get_records_select('lesson_timer', $select, $params, '', 'id');
1636 if (!empty($timers)) {
1637 $updates->usertimers->updated = true;
1638 $updates->usertimers->itemids = array_keys($timers);
1645 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1647 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1648 * is not displayed on the block.
1650 * @param calendar_event $event
1651 * @param \core_calendar\action_factory $factory
1652 * @return \core_calendar\local\event\entities\action_interface|null
1654 function mod_lesson_core_calendar_provide_event_action(calendar_event $event,
1655 \core_calendar\action_factory $factory) {
1656 global $DB, $CFG, $USER;
1657 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
1659 $cm = get_fast_modinfo($event->courseid)->instances['lesson'][$event->instance];
1660 $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST));
1662 if ($lesson->count_user_retries($USER->id)) {
1663 // If the user has attempted the lesson then there is no further action for the user.
1668 $lesson->update_effective_access($USER->id);
1670 return $factory->create_instance(
1671 get_string('startlesson', 'lesson'),
1672 new \moodle_url('/mod/lesson/view.php', ['id' => $cm->id]),
1674 $lesson->is_accessible()
1679 * Add a get_coursemodule_info function in case any lesson type wants to add 'extra' information
1680 * for the course (see resource).
1682 * Given a course_module object, this function returns any "extra" information that may be needed
1683 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1685 * @param stdClass $coursemodule The coursemodule object (record).
1686 * @return cached_cm_info An object on information that the courses
1687 * will know about (most noticeably, an icon).
1689 function lesson_get_coursemodule_info($coursemodule) {
1692 $dbparams = ['id' => $coursemodule->instance];
1693 $fields = 'id, name, intro, introformat, completionendreached, completiontimespent';
1694 if (!$lesson = $DB->get_record('lesson', $dbparams, $fields)) {
1698 $result = new cached_cm_info();
1699 $result->name = $lesson->name;
1701 if ($coursemodule->showdescription) {
1702 // Convert intro to html. Do not filter cached version, filters run at display time.
1703 $result->content = format_module_intro('lesson', $lesson, $coursemodule->id, false);
1706 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1707 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1708 $result->customdata['customcompletionrules']['completionendreached'] = $lesson->completionendreached;
1709 $result->customdata['customcompletionrules']['completiontimespent'] = $lesson->completiontimespent;
1716 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1718 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1719 * @return array $descriptions the array of descriptions for the custom rules.
1721 function mod_lesson_get_completion_active_rule_descriptions($cm) {
1722 // Values will be present in cm_info, and we assume these are up to date.
1723 if (empty($cm->customdata['customcompletionrules'])
1724 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1729 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1731 case 'completionendreached':
1735 $descriptions[] = get_string('completionendreached_desc', 'lesson', $val);
1737 case 'completiontimespent':
1741 $descriptions[] = get_string('completiontimespentdesc', 'lesson', format_time($val));
1747 return $descriptions;