Merge branch 'MDL-33509-master' of git://github.com/mihailges/moodle
[moodle.git] / mod / lesson / lib.php
blobfb554857107381cfe19bb85b7f086b28bfe14f59
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
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/>.
18 /**
19 * Standard library of functions and constants for lesson
21 * @package mod_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
24 **/
26 defined('MOODLE_INTERNAL') || die();
28 // Event types.
29 define('LESSON_EVENT_TYPE_OPEN', 'open');
30 define('LESSON_EVENT_TYPE_CLOSE', 'close');
32 /* Do not include any libraries here! */
34 /**
35 * Given an object containing all the necessary data,
36 * (defined by the form in mod_form.php) this function
37 * will create a new instance and return the id number
38 * of the new instance.
40 * @global object
41 * @global object
42 * @param object $lesson Lesson post data from the form
43 * @return int
44 **/
45 function lesson_add_instance($data, $mform) {
46 global $DB;
48 $cmid = $data->coursemodule;
49 $draftitemid = $data->mediafile;
50 $context = context_module::instance($cmid);
52 lesson_process_pre_save($data);
54 unset($data->mediafile);
55 $lessonid = $DB->insert_record("lesson", $data);
56 $data->id = $lessonid;
58 lesson_update_media_file($lessonid, $context, $draftitemid);
60 lesson_process_post_save($data);
62 lesson_grade_item_update($data);
64 return $lessonid;
67 /**
68 * Given an object containing all the necessary data,
69 * (defined by the form in mod_form.php) this function
70 * will update an existing instance with new data.
72 * @global object
73 * @param object $lesson Lesson post data from the form
74 * @return boolean
75 **/
76 function lesson_update_instance($data, $mform) {
77 global $DB;
79 $data->id = $data->instance;
80 $cmid = $data->coursemodule;
81 $draftitemid = $data->mediafile;
82 $context = context_module::instance($cmid);
84 lesson_process_pre_save($data);
86 unset($data->mediafile);
87 $DB->update_record("lesson", $data);
89 lesson_update_media_file($data->id, $context, $draftitemid);
91 lesson_process_post_save($data);
93 // update grade item definition
94 lesson_grade_item_update($data);
96 // update grades - TODO: do it only when grading style changes
97 lesson_update_grades($data, 0, false);
99 return true;
103 * This function updates the events associated to the lesson.
104 * If $override is non-zero, then it updates only the events
105 * associated with the specified override.
107 * @uses LESSON_MAX_EVENT_LENGTH
108 * @param object $lesson the lesson object.
109 * @param object $override (optional) limit to a specific override
111 function lesson_update_events($lesson, $override = null) {
112 global $CFG, $DB;
114 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
115 require_once($CFG->dirroot . '/calendar/lib.php');
117 // Load the old events relating to this lesson.
118 $conds = array('modulename' => 'lesson',
119 'instance' => $lesson->id);
120 if (!empty($override)) {
121 // Only load events for this override.
122 if (isset($override->userid)) {
123 $conds['userid'] = $override->userid;
124 } else {
125 $conds['groupid'] = $override->groupid;
128 $oldevents = $DB->get_records('event', $conds, 'id ASC');
130 // Now make a to-do list of all that needs to be updated.
131 if (empty($override)) {
132 // We are updating the primary settings for the lesson, so we need to add all the overrides.
133 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $lesson->id), 'id ASC');
134 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
135 // list contains the original (non-override) event for the module. If this is not included
136 // the logic below will end up updating the wrong row when we try to reconcile this $overrides
137 // list against the $oldevents list.
138 array_unshift($overrides, new stdClass());
139 } else {
140 // Just do the one override.
141 $overrides = array($override);
144 // Get group override priorities.
145 $grouppriorities = lesson_get_group_override_priorities($lesson->id);
147 foreach ($overrides as $current) {
148 $groupid = isset($current->groupid) ? $current->groupid : 0;
149 $userid = isset($current->userid) ? $current->userid : 0;
150 $available = isset($current->available) ? $current->available : $lesson->available;
151 $deadline = isset($current->deadline) ? $current->deadline : $lesson->deadline;
153 // Only add open/close events for an override if they differ from the lesson default.
154 $addopen = empty($current->id) || !empty($current->available);
155 $addclose = empty($current->id) || !empty($current->deadline);
157 if (!empty($lesson->coursemodule)) {
158 $cmid = $lesson->coursemodule;
159 } else {
160 $cmid = get_coursemodule_from_instance('lesson', $lesson->id, $lesson->course)->id;
163 $event = new stdClass();
164 $event->type = !$deadline ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
165 $event->description = format_module_intro('lesson', $lesson, $cmid);
166 // Events module won't show user events when the courseid is nonzero.
167 $event->courseid = ($userid) ? 0 : $lesson->course;
168 $event->groupid = $groupid;
169 $event->userid = $userid;
170 $event->modulename = 'lesson';
171 $event->instance = $lesson->id;
172 $event->timestart = $available;
173 $event->timeduration = max($deadline - $available, 0);
174 $event->timesort = $available;
175 $event->visible = instance_is_visible('lesson', $lesson);
176 $event->eventtype = LESSON_EVENT_TYPE_OPEN;
177 $event->priority = null;
179 // Determine the event name and priority.
180 if ($groupid) {
181 // Group override event.
182 $params = new stdClass();
183 $params->lesson = $lesson->name;
184 $params->group = groups_get_group_name($groupid);
185 if ($params->group === false) {
186 // Group doesn't exist, just skip it.
187 continue;
189 $eventname = get_string('overridegroupeventname', 'lesson', $params);
190 // Set group override priority.
191 if ($grouppriorities !== null) {
192 $openpriorities = $grouppriorities['open'];
193 if (isset($openpriorities[$available])) {
194 $event->priority = $openpriorities[$available];
197 } else if ($userid) {
198 // User override event.
199 $params = new stdClass();
200 $params->lesson = $lesson->name;
201 $eventname = get_string('overrideusereventname', 'lesson', $params);
202 // Set user override priority.
203 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
204 } else {
205 // The parent event.
206 $eventname = $lesson->name;
209 if ($addopen or $addclose) {
210 // Separate start and end events.
211 $event->timeduration = 0;
212 if ($available && $addopen) {
213 if ($oldevent = array_shift($oldevents)) {
214 $event->id = $oldevent->id;
215 } else {
216 unset($event->id);
218 $event->name = get_string('lessoneventopens', 'lesson', $eventname);
219 // The method calendar_event::create will reuse a db record if the id field is set.
220 calendar_event::create($event);
222 if ($deadline && $addclose) {
223 if ($oldevent = array_shift($oldevents)) {
224 $event->id = $oldevent->id;
225 } else {
226 unset($event->id);
228 $event->type = CALENDAR_EVENT_TYPE_ACTION;
229 $event->name = get_string('lessoneventcloses', 'lesson', $eventname);
230 $event->timestart = $deadline;
231 $event->timesort = $deadline;
232 $event->eventtype = LESSON_EVENT_TYPE_CLOSE;
233 if ($groupid && $grouppriorities !== null) {
234 $closepriorities = $grouppriorities['close'];
235 if (isset($closepriorities[$deadline])) {
236 $event->priority = $closepriorities[$deadline];
239 calendar_event::create($event);
244 // Delete any leftover events.
245 foreach ($oldevents as $badevent) {
246 $badevent = calendar_event::load($badevent);
247 $badevent->delete();
252 * Calculates the priorities of timeopen and timeclose values for group overrides for a lesson.
254 * @param int $lessonid The lesson ID.
255 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
257 function lesson_get_group_override_priorities($lessonid) {
258 global $DB;
260 // Fetch group overrides.
261 $where = 'lessonid = :lessonid AND groupid IS NOT NULL';
262 $params = ['lessonid' => $lessonid];
263 $overrides = $DB->get_records_select('lesson_overrides', $where, $params, '', 'id, groupid, available, deadline');
264 if (!$overrides) {
265 return null;
268 $grouptimeopen = [];
269 $grouptimeclose = [];
270 foreach ($overrides as $override) {
271 if ($override->available !== null && !in_array($override->available, $grouptimeopen)) {
272 $grouptimeopen[] = $override->available;
274 if ($override->deadline !== null && !in_array($override->deadline, $grouptimeclose)) {
275 $grouptimeclose[] = $override->deadline;
279 // Sort open times in ascending manner. The earlier open time gets higher priority.
280 sort($grouptimeopen);
281 // Set priorities.
282 $opengrouppriorities = [];
283 $openpriority = 1;
284 foreach ($grouptimeopen as $timeopen) {
285 $opengrouppriorities[$timeopen] = $openpriority++;
288 // Sort close times in descending manner. The later close time gets higher priority.
289 rsort($grouptimeclose);
290 // Set priorities.
291 $closegrouppriorities = [];
292 $closepriority = 1;
293 foreach ($grouptimeclose as $timeclose) {
294 $closegrouppriorities[$timeclose] = $closepriority++;
297 return [
298 'open' => $opengrouppriorities,
299 'close' => $closegrouppriorities
304 * This standard function will check all instances of this module
305 * and make sure there are up-to-date events created for each of them.
306 * If courseid = 0, then every lesson event in the site is checked, else
307 * only lesson events belonging to the course specified are checked.
308 * This function is used, in its new format, by restore_refresh_events()
310 * @param int $courseid
311 * @param int|stdClass $instance Lesson module instance or ID.
312 * @param int|stdClass $cm Course module object or ID (not used in this module).
313 * @return bool
315 function lesson_refresh_events($courseid = 0, $instance = null, $cm = null) {
316 global $DB;
318 // If we have instance information then we can just update the one event instead of updating all events.
319 if (isset($instance)) {
320 if (!is_object($instance)) {
321 $instance = $DB->get_record('lesson', array('id' => $instance), '*', MUST_EXIST);
323 lesson_update_events($instance);
324 return true;
327 if ($courseid == 0) {
328 if (!$lessons = $DB->get_records('lesson')) {
329 return true;
331 } else {
332 if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) {
333 return true;
337 foreach ($lessons as $lesson) {
338 lesson_update_events($lesson);
341 return true;
345 * Given an ID of an instance of this module,
346 * this function will permanently delete the instance
347 * and any data that depends on it.
349 * @global object
350 * @param int $id
351 * @return bool
353 function lesson_delete_instance($id) {
354 global $DB, $CFG;
355 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
357 $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST);
358 $lesson = new lesson($lesson);
359 return $lesson->delete();
363 * Return a small object with summary information about what a
364 * user has done with a given particular instance of this module
365 * Used for user activity reports.
366 * $return->time = the time they did it
367 * $return->info = a short text description
369 * @global object
370 * @param object $course
371 * @param object $user
372 * @param object $mod
373 * @param object $lesson
374 * @return object
376 function lesson_user_outline($course, $user, $mod, $lesson) {
377 global $CFG, $DB;
379 require_once("$CFG->libdir/gradelib.php");
380 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
381 $return = new stdClass();
383 if (empty($grades->items[0]->grades)) {
384 $return->info = get_string("nolessonattempts", "lesson");
385 } else {
386 $grade = reset($grades->items[0]->grades);
387 if (empty($grade->grade)) {
389 // Check to see if it an ungraded / incomplete attempt.
390 $sql = "SELECT *
391 FROM {lesson_timer}
392 WHERE lessonid = :lessonid
393 AND userid = :userid
394 ORDER BY starttime DESC";
395 $params = array('lessonid' => $lesson->id, 'userid' => $user->id);
397 if ($attempts = $DB->get_records_sql($sql, $params, 0, 1)) {
398 $attempt = reset($attempts);
399 if ($attempt->completed) {
400 $return->info = get_string("completed", "lesson");
401 } else {
402 $return->info = get_string("notyetcompleted", "lesson");
404 $return->time = $attempt->lessontime;
405 } else {
406 $return->info = get_string("nolessonattempts", "lesson");
408 } else {
409 $return->info = get_string("grade") . ': ' . $grade->str_long_grade;
411 // Datesubmitted == time created. dategraded == time modified or time overridden.
412 // If grade was last modified by the user themselves use date graded. Otherwise use date submitted.
413 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
414 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
415 $return->time = $grade->dategraded;
416 } else {
417 $return->time = $grade->datesubmitted;
421 return $return;
425 * Print a detailed representation of what a user has done with
426 * a given particular instance of this module, for user activity reports.
428 * @global object
429 * @param object $course
430 * @param object $user
431 * @param object $mod
432 * @param object $lesson
433 * @return bool
435 function lesson_user_complete($course, $user, $mod, $lesson) {
436 global $DB, $OUTPUT, $CFG;
438 require_once("$CFG->libdir/gradelib.php");
440 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
442 // Display the grade and feedback.
443 if (empty($grades->items[0]->grades)) {
444 echo $OUTPUT->container(get_string("nolessonattempts", "lesson"));
445 } else {
446 $grade = reset($grades->items[0]->grades);
447 if (empty($grade->grade)) {
448 // Check to see if it an ungraded / incomplete attempt.
449 $sql = "SELECT *
450 FROM {lesson_timer}
451 WHERE lessonid = :lessonid
452 AND userid = :userid
453 ORDER by starttime desc";
454 $params = array('lessonid' => $lesson->id, 'userid' => $user->id);
456 if ($attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE)) {
457 if ($attempt->completed) {
458 $status = get_string("completed", "lesson");
459 } else {
460 $status = get_string("notyetcompleted", "lesson");
462 } else {
463 $status = get_string("nolessonattempts", "lesson");
465 } else {
466 $status = get_string("grade") . ': ' . $grade->str_long_grade;
469 // Display the grade or lesson status if there isn't one.
470 echo $OUTPUT->container($status);
472 if ($grade->str_feedback) {
473 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
477 // Display the lesson progress.
478 // Attempt, pages viewed, questions answered, correct answers, time.
479 $params = array ("lessonid" => $lesson->id, "userid" => $user->id);
480 $attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
481 $branches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
482 if (!empty($attempts) or !empty($branches)) {
483 echo $OUTPUT->box_start();
484 $table = new html_table();
485 // Table Headings.
486 $table->head = array (get_string("attemptheader", "lesson"),
487 get_string("totalpagesviewedheader", "lesson"),
488 get_string("numberofpagesviewedheader", "lesson"),
489 get_string("numberofcorrectanswersheader", "lesson"),
490 get_string("time"));
491 $table->width = "100%";
492 $table->align = array ("center", "center", "center", "center", "center");
493 $table->size = array ("*", "*", "*", "*", "*");
494 $table->cellpadding = 2;
495 $table->cellspacing = 0;
497 $retry = 0;
498 $nquestions = 0;
499 $npages = 0;
500 $ncorrect = 0;
502 // Filter question pages (from lesson_attempts).
503 foreach ($attempts as $attempt) {
504 if ($attempt->retry == $retry) {
505 $npages++;
506 $nquestions++;
507 if ($attempt->correct) {
508 $ncorrect++;
510 $timeseen = $attempt->timeseen;
511 } else {
512 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
513 $retry++;
514 $nquestions = 1;
515 $npages = 1;
516 if ($attempt->correct) {
517 $ncorrect = 1;
518 } else {
519 $ncorrect = 0;
524 // Filter content pages (from lesson_branch).
525 foreach ($branches as $branch) {
526 if ($branch->retry == $retry) {
527 $npages++;
529 $timeseen = $branch->timeseen;
530 } else {
531 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
532 $retry++;
533 $npages = 1;
536 if ($npages > 0) {
537 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
539 echo html_writer::table($table);
540 echo $OUTPUT->box_end();
543 return true;
547 * Prints lesson summaries on MyMoodle Page
549 * Prints lesson name, due date and attempt information on
550 * lessons that have a deadline that has not already passed
551 * and it is available for taking.
553 * @deprecated since 3.3
554 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
555 * @global object
556 * @global stdClass
557 * @global object
558 * @uses CONTEXT_MODULE
559 * @param array $courses An array of course objects to get lesson instances from
560 * @param array $htmlarray Store overview output array( course ID => 'lesson' => HTML output )
561 * @return void
563 function lesson_print_overview($courses, &$htmlarray) {
564 global $USER, $CFG, $DB, $OUTPUT;
566 debugging('The function lesson_print_overview() is now deprecated.', DEBUG_DEVELOPER);
568 if (!$lessons = get_all_instances_in_courses('lesson', $courses)) {
569 return;
572 // Get all of the current users attempts on all lessons.
573 $params = array($USER->id);
574 $sql = 'SELECT lessonid, userid, count(userid) as attempts
575 FROM {lesson_grades}
576 WHERE userid = ?
577 GROUP BY lessonid, userid';
578 $allattempts = $DB->get_records_sql($sql, $params);
579 $completedattempts = array();
580 foreach ($allattempts as $myattempt) {
581 $completedattempts[$myattempt->lessonid] = $myattempt->attempts;
584 // Get the current course ID.
585 $listoflessons = array();
586 foreach ($lessons as $lesson) {
587 $listoflessons[] = $lesson->id;
589 // Get the last page viewed by the current user for every lesson in this course.
590 list($insql, $inparams) = $DB->get_in_or_equal($listoflessons, SQL_PARAMS_NAMED);
591 $dbparams = array_merge($inparams, array('userid' => $USER->id));
593 // Get the lesson attempts for the user that have the maximum 'timeseen' value.
594 $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.answerid as nextpageid, p.qtype ";
595 $from = "FROM {lesson_attempts} l
596 JOIN (
597 SELECT idselect.lessonid, idselect.userid, MAX(idselect.id) AS id
598 FROM {lesson_attempts} idselect
599 JOIN (
600 SELECT lessonid, userid, MAX(timeseen) AS timeseen
601 FROM {lesson_attempts}
602 WHERE userid = :userid
603 AND lessonid $insql
604 GROUP BY userid, lessonid
605 ) timeselect
606 ON timeselect.timeseen = idselect.timeseen
607 AND timeselect.userid = idselect.userid
608 AND timeselect.lessonid = idselect.lessonid
609 GROUP BY idselect.userid, idselect.lessonid
610 ) aid
611 ON l.id = aid.id
612 JOIN {lesson_pages} p
613 ON l.pageid = p.id ";
614 $lastattempts = $DB->get_records_sql($select . $from, $dbparams);
616 // Now, get the lesson branches for the user that have the maximum 'timeseen' value.
617 $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.nextpageid, p.qtype ";
618 $from = str_replace('{lesson_attempts}', '{lesson_branch}', $from);
619 $lastbranches = $DB->get_records_sql($select . $from, $dbparams);
621 $lastviewed = array();
622 foreach ($lastattempts as $lastattempt) {
623 $lastviewed[$lastattempt->lessonid] = $lastattempt;
626 // Go through the branch times and record the 'timeseen' value if it doesn't exist
627 // for the lesson, or replace it if it exceeds the current recorded time.
628 foreach ($lastbranches as $lastbranch) {
629 if (!isset($lastviewed[$lastbranch->lessonid])) {
630 $lastviewed[$lastbranch->lessonid] = $lastbranch;
631 } else if ($lastviewed[$lastbranch->lessonid]->timeseen < $lastbranch->timeseen) {
632 $lastviewed[$lastbranch->lessonid] = $lastbranch;
636 // Since we have lessons in this course, now include the constants we need.
637 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
639 $now = time();
640 foreach ($lessons as $lesson) {
641 if ($lesson->deadline != 0 // The lesson has a deadline
642 and $lesson->deadline >= $now // And it is before the deadline has been met
643 and ($lesson->available == 0 or $lesson->available <= $now)) { // And the lesson is available
645 // Visibility.
646 $class = (!$lesson->visible) ? 'dimmed' : '';
648 // Context.
649 $context = context_module::instance($lesson->coursemodule);
651 // Link to activity.
652 $url = new moodle_url('/mod/lesson/view.php', array('id' => $lesson->coursemodule));
653 $url = html_writer::link($url, format_string($lesson->name, true, array('context' => $context)), array('class' => $class));
654 $str = $OUTPUT->box(get_string('lessonname', 'lesson', $url), 'name');
656 // Deadline.
657 $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info');
659 // Attempt information.
660 if (has_capability('mod/lesson:manage', $context)) {
661 // This is a teacher, Get the Number of user attempts.
662 $attempts = $DB->count_records('lesson_grades', array('lessonid' => $lesson->id));
663 $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info');
664 $str = $OUTPUT->box($str, 'lesson overview');
665 } else {
666 // This is a student, See if the user has at least started the lesson.
667 if (isset($lastviewed[$lesson->id]->timeseen)) {
668 // See if the user has finished this attempt.
669 if (isset($completedattempts[$lesson->id]) &&
670 ($completedattempts[$lesson->id] == ($lastviewed[$lesson->id]->retry + 1))) {
671 // Are additional attempts allowed?
672 if ($lesson->retake) {
673 // User can retake the lesson.
674 $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info');
675 $str = $OUTPUT->box($str, 'lesson overview');
676 } else {
677 // User has completed the lesson and no retakes are allowed.
678 $str = '';
681 } else {
682 // The last attempt was not finished or the lesson does not contain questions.
683 // See if the last page viewed was a branchtable.
684 require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php');
685 if ($lastviewed[$lesson->id]->qtype == LESSON_PAGE_BRANCHTABLE) {
686 // See if the next pageid is the end of lesson.
687 if ($lastviewed[$lesson->id]->nextpageid == LESSON_EOL) {
688 // The last page viewed was the End of Lesson.
689 if ($lesson->retake) {
690 // User can retake the lesson.
691 $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info');
692 $str = $OUTPUT->box($str, 'lesson overview');
693 } else {
694 // User has completed the lesson and no retakes are allowed.
695 $str = '';
698 } else {
699 // The last page viewed was NOT the end of lesson.
700 $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info');
701 $str = $OUTPUT->box($str, 'lesson overview');
704 } else {
705 // Last page was a question page, so the attempt is not completed yet.
706 $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info');
707 $str = $OUTPUT->box($str, 'lesson overview');
711 } else {
712 // User has not yet started this lesson.
713 $str .= $OUTPUT->box(get_string('nolessonattempts', 'lesson'), 'info');
714 $str = $OUTPUT->box($str, 'lesson overview');
717 if (!empty($str)) {
718 if (empty($htmlarray[$lesson->course]['lesson'])) {
719 $htmlarray[$lesson->course]['lesson'] = $str;
720 } else {
721 $htmlarray[$lesson->course]['lesson'] .= $str;
729 * Function to be run periodically according to the moodle cron
730 * This function searches for things that need to be done, such
731 * as sending out mail, toggling flags etc ...
732 * @global stdClass
733 * @return bool true
735 function lesson_cron () {
736 global $CFG;
738 return true;
742 * Return grade for given user or all users.
744 * @global stdClass
745 * @global object
746 * @param int $lessonid id of lesson
747 * @param int $userid optional user id, 0 means all users
748 * @return array array of grades, false if none
750 function lesson_get_user_grades($lesson, $userid=0) {
751 global $CFG, $DB;
753 $params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id);
755 if (!empty($userid)) {
756 $params["userid"] = $userid;
757 $params["userid2"] = $userid;
758 $user = "AND u.id = :userid";
759 $fuser = "AND uu.id = :userid2";
761 else {
762 $user="";
763 $fuser="";
766 if ($lesson->retake) {
767 if ($lesson->usemaxgrade) {
768 $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade
769 FROM {user} u, {lesson_grades} g
770 WHERE u.id = g.userid AND g.lessonid = :lessonid
771 $user
772 GROUP BY u.id";
773 } else {
774 $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade
775 FROM {user} u, {lesson_grades} g
776 WHERE u.id = g.userid AND g.lessonid = :lessonid
777 $user
778 GROUP BY u.id";
780 unset($params['lessonid2']);
781 unset($params['userid2']);
782 } else {
783 // use only first attempts (with lowest id in lesson_grades table)
784 $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted
785 FROM {user} uu, {lesson_grades} gg
786 WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2
787 $fuser
788 GROUP BY uu.id";
790 $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade
791 FROM {user} u, {lesson_grades} g, ($firstonly) f
792 WHERE u.id = g.userid AND g.lessonid = :lessonid
793 AND g.id = f.firstcompleted AND g.userid=f.userid
794 $user";
797 return $DB->get_records_sql($sql, $params);
801 * Update grades in central gradebook
803 * @category grade
804 * @param object $lesson
805 * @param int $userid specific user only, 0 means all
806 * @param bool $nullifnone
808 function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
809 global $CFG, $DB;
810 require_once($CFG->libdir.'/gradelib.php');
812 if ($lesson->grade == 0 || $lesson->practice) {
813 lesson_grade_item_update($lesson);
815 } else if ($grades = lesson_get_user_grades($lesson, $userid)) {
816 lesson_grade_item_update($lesson, $grades);
818 } else if ($userid and $nullifnone) {
819 $grade = new stdClass();
820 $grade->userid = $userid;
821 $grade->rawgrade = null;
822 lesson_grade_item_update($lesson, $grade);
824 } else {
825 lesson_grade_item_update($lesson);
830 * Create grade item for given lesson
832 * @category grade
833 * @uses GRADE_TYPE_VALUE
834 * @uses GRADE_TYPE_NONE
835 * @param object $lesson object with extra cmidnumber
836 * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
837 * @return int 0 if ok, error code otherwise
839 function lesson_grade_item_update($lesson, $grades=null) {
840 global $CFG;
841 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
842 require_once($CFG->libdir.'/gradelib.php');
845 if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present
846 $params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber);
847 } else {
848 $params = array('itemname'=>$lesson->name);
851 if (!$lesson->practice and $lesson->grade > 0) {
852 $params['gradetype'] = GRADE_TYPE_VALUE;
853 $params['grademax'] = $lesson->grade;
854 $params['grademin'] = 0;
855 } else if (!$lesson->practice and $lesson->grade < 0) {
856 $params['gradetype'] = GRADE_TYPE_SCALE;
857 $params['scaleid'] = -$lesson->grade;
859 // Make sure current grade fetched correctly from $grades
860 $currentgrade = null;
861 if (!empty($grades)) {
862 if (is_array($grades)) {
863 $currentgrade = reset($grades);
864 } else {
865 $currentgrade = $grades;
869 // When converting a score to a scale, use scale's grade maximum to calculate it.
870 if (!empty($currentgrade) && $currentgrade->rawgrade !== null) {
871 $grade = grade_get_grades($lesson->course, 'mod', 'lesson', $lesson->id, $currentgrade->userid);
872 $params['grademax'] = reset($grade->items)->grademax;
874 } else {
875 $params['gradetype'] = GRADE_TYPE_NONE;
878 if ($grades === 'reset') {
879 $params['reset'] = true;
880 $grades = null;
881 } else if (!empty($grades)) {
882 // Need to calculate raw grade (Note: $grades has many forms)
883 if (is_object($grades)) {
884 $grades = array($grades->userid => $grades);
885 } else if (array_key_exists('userid', $grades)) {
886 $grades = array($grades['userid'] => $grades);
888 foreach ($grades as $key => $grade) {
889 if (!is_array($grade)) {
890 $grades[$key] = $grade = (array) $grade;
892 //check raw grade isnt null otherwise we erroneously insert a grade of 0
893 if ($grade['rawgrade'] !== null) {
894 $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100);
895 } else {
896 //setting rawgrade to null just in case user is deleting a grade
897 $grades[$key]['rawgrade'] = null;
902 return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params);
906 * List the actions that correspond to a view of this module.
907 * This is used by the participation report.
909 * Note: This is not used by new logging system. Event with
910 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
911 * be considered as view action.
913 * @return array
915 function lesson_get_view_actions() {
916 return array('view','view all');
920 * List the actions that correspond to a post of this module.
921 * This is used by the participation report.
923 * Note: This is not used by new logging system. Event with
924 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
925 * will be considered as post action.
927 * @return array
929 function lesson_get_post_actions() {
930 return array('end','start');
934 * Runs any processes that must run before
935 * a lesson insert/update
937 * @global object
938 * @param object $lesson Lesson form data
939 * @return void
941 function lesson_process_pre_save(&$lesson) {
942 global $DB;
944 $lesson->timemodified = time();
946 if (empty($lesson->timelimit)) {
947 $lesson->timelimit = 0;
949 if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) {
950 $lesson->timespent = 0;
952 if (!isset($lesson->completed)) {
953 $lesson->completed = 0;
955 if (empty($lesson->gradebetterthan) or !is_numeric($lesson->gradebetterthan) or $lesson->gradebetterthan < 0) {
956 $lesson->gradebetterthan = 0;
957 } else if ($lesson->gradebetterthan > 100) {
958 $lesson->gradebetterthan = 100;
961 if (empty($lesson->width)) {
962 $lesson->width = 640;
964 if (empty($lesson->height)) {
965 $lesson->height = 480;
967 if (empty($lesson->bgcolor)) {
968 $lesson->bgcolor = '#FFFFFF';
971 // Conditions for dependency
972 $conditions = new stdClass;
973 $conditions->timespent = $lesson->timespent;
974 $conditions->completed = $lesson->completed;
975 $conditions->gradebetterthan = $lesson->gradebetterthan;
976 $lesson->conditions = serialize($conditions);
977 unset($lesson->timespent);
978 unset($lesson->completed);
979 unset($lesson->gradebetterthan);
981 if (empty($lesson->password)) {
982 unset($lesson->password);
987 * Runs any processes that must be run
988 * after a lesson insert/update
990 * @global object
991 * @param object $lesson Lesson form data
992 * @return void
994 function lesson_process_post_save(&$lesson) {
995 // Update the events relating to this lesson.
996 lesson_update_events($lesson);
997 $completionexpected = (!empty($lesson->completionexpected)) ? $lesson->completionexpected : null;
998 \core_completion\api::update_completion_date_event($lesson->coursemodule, 'lesson', $lesson, $completionexpected);
1003 * Implementation of the function for printing the form elements that control
1004 * whether the course reset functionality affects the lesson.
1006 * @param $mform form passed by reference
1008 function lesson_reset_course_form_definition(&$mform) {
1009 $mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson'));
1010 $mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts','lesson'));
1011 $mform->addElement('advcheckbox', 'reset_lesson_user_overrides',
1012 get_string('removealluseroverrides', 'lesson'));
1013 $mform->addElement('advcheckbox', 'reset_lesson_group_overrides',
1014 get_string('removeallgroupoverrides', 'lesson'));
1018 * Course reset form defaults.
1019 * @param object $course
1020 * @return array
1022 function lesson_reset_course_form_defaults($course) {
1023 return array('reset_lesson' => 1,
1024 'reset_lesson_group_overrides' => 1,
1025 'reset_lesson_user_overrides' => 1);
1029 * Removes all grades from gradebook
1031 * @global stdClass
1032 * @global object
1033 * @param int $courseid
1034 * @param string optional type
1036 function lesson_reset_gradebook($courseid, $type='') {
1037 global $CFG, $DB;
1039 $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
1040 FROM {lesson} l, {course_modules} cm, {modules} m
1041 WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course";
1042 $params = array ("course" => $courseid);
1043 if ($lessons = $DB->get_records_sql($sql,$params)) {
1044 foreach ($lessons as $lesson) {
1045 lesson_grade_item_update($lesson, 'reset');
1051 * Actual implementation of the reset course functionality, delete all the
1052 * lesson attempts for course $data->courseid.
1054 * @global stdClass
1055 * @global object
1056 * @param object $data the data submitted from the reset course.
1057 * @return array status array
1059 function lesson_reset_userdata($data) {
1060 global $CFG, $DB;
1062 $componentstr = get_string('modulenameplural', 'lesson');
1063 $status = array();
1065 if (!empty($data->reset_lesson)) {
1066 $lessonssql = "SELECT l.id
1067 FROM {lesson} l
1068 WHERE l.course=:course";
1070 $params = array ("course" => $data->courseid);
1071 $lessons = $DB->get_records_sql($lessonssql, $params);
1073 // Get rid of attempts files.
1074 $fs = get_file_storage();
1075 if ($lessons) {
1076 foreach ($lessons as $lessonid => $unused) {
1077 if (!$cm = get_coursemodule_from_instance('lesson', $lessonid)) {
1078 continue;
1080 $context = context_module::instance($cm->id);
1081 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses');
1085 $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params);
1086 $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params);
1087 $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params);
1088 $DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params);
1090 // remove all grades from gradebook
1091 if (empty($data->reset_gradebook_grades)) {
1092 lesson_reset_gradebook($data->courseid);
1095 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false);
1098 // Remove user overrides.
1099 if (!empty($data->reset_lesson_user_overrides)) {
1100 $DB->delete_records_select('lesson_overrides',
1101 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1102 $status[] = array(
1103 'component' => $componentstr,
1104 'item' => get_string('useroverridesdeleted', 'lesson'),
1105 'error' => false);
1107 // Remove group overrides.
1108 if (!empty($data->reset_lesson_group_overrides)) {
1109 $DB->delete_records_select('lesson_overrides',
1110 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1111 $status[] = array(
1112 'component' => $componentstr,
1113 'item' => get_string('groupoverridesdeleted', 'lesson'),
1114 'error' => false);
1116 /// updating dates - shift may be negative too
1117 if ($data->timeshift) {
1118 $DB->execute("UPDATE {lesson_overrides}
1119 SET available = available + ?
1120 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
1121 AND available <> 0", array($data->timeshift, $data->courseid));
1122 $DB->execute("UPDATE {lesson_overrides}
1123 SET deadline = deadline + ?
1124 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
1125 AND deadline <> 0", array($data->timeshift, $data->courseid));
1127 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1128 // See MDL-9367.
1129 shift_course_mod_dates('lesson', array('available', 'deadline'), $data->timeshift, $data->courseid);
1130 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
1133 return $status;
1137 * Returns all other caps used in module
1138 * @return array
1140 function lesson_get_extra_capabilities() {
1141 return array('moodle/site:accessallgroups');
1145 * @uses FEATURE_GROUPS
1146 * @uses FEATURE_GROUPINGS
1147 * @uses FEATURE_MOD_INTRO
1148 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1149 * @uses FEATURE_GRADE_HAS_GRADE
1150 * @uses FEATURE_GRADE_OUTCOMES
1151 * @param string $feature FEATURE_xx constant for requested feature
1152 * @return mixed True if module supports feature, false if not, null if doesn't know
1154 function lesson_supports($feature) {
1155 switch($feature) {
1156 case FEATURE_GROUPS:
1157 return true;
1158 case FEATURE_GROUPINGS:
1159 return true;
1160 case FEATURE_MOD_INTRO:
1161 return true;
1162 case FEATURE_COMPLETION_TRACKS_VIEWS:
1163 return true;
1164 case FEATURE_GRADE_HAS_GRADE:
1165 return true;
1166 case FEATURE_COMPLETION_HAS_RULES:
1167 return true;
1168 case FEATURE_GRADE_OUTCOMES:
1169 return true;
1170 case FEATURE_BACKUP_MOODLE2:
1171 return true;
1172 case FEATURE_SHOW_DESCRIPTION:
1173 return true;
1174 default:
1175 return null;
1180 * Obtains the automatic completion state for this lesson based on any conditions
1181 * in lesson settings.
1183 * @param object $course Course
1184 * @param object $cm course-module
1185 * @param int $userid User ID
1186 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1187 * @return bool True if completed, false if not, $type if conditions not set.
1189 function lesson_get_completion_state($course, $cm, $userid, $type) {
1190 global $CFG, $DB;
1192 // Get lesson details.
1193 $lesson = $DB->get_record('lesson', array('id' => $cm->instance), '*',
1194 MUST_EXIST);
1196 $result = $type; // Default return value.
1197 // If completion option is enabled, evaluate it and return true/false.
1198 if ($lesson->completionendreached) {
1199 $value = $DB->record_exists('lesson_timer', array(
1200 'lessonid' => $lesson->id, 'userid' => $userid, 'completed' => 1));
1201 if ($type == COMPLETION_AND) {
1202 $result = $result && $value;
1203 } else {
1204 $result = $result || $value;
1207 if ($lesson->completiontimespent != 0) {
1208 $duration = $DB->get_field_sql(
1209 "SELECT SUM(lessontime - starttime)
1210 FROM {lesson_timer}
1211 WHERE lessonid = :lessonid
1212 AND userid = :userid",
1213 array('userid' => $userid, 'lessonid' => $lesson->id));
1214 if (!$duration) {
1215 $duration = 0;
1217 if ($type == COMPLETION_AND) {
1218 $result = $result && ($lesson->completiontimespent < $duration);
1219 } else {
1220 $result = $result || ($lesson->completiontimespent < $duration);
1223 return $result;
1226 * This function extends the settings navigation block for the site.
1228 * It is safe to rely on PAGE here as we will only ever be within the module
1229 * context when this is called
1231 * @param settings_navigation $settings
1232 * @param navigation_node $lessonnode
1234 function lesson_extend_settings_navigation($settings, $lessonnode) {
1235 global $PAGE, $DB;
1237 // We want to add these new nodes after the Edit settings node, and before the
1238 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1239 $keys = $lessonnode->get_children_key_list();
1240 $beforekey = null;
1241 $i = array_search('modedit', $keys);
1242 if ($i === false and array_key_exists(0, $keys)) {
1243 $beforekey = $keys[0];
1244 } else if (array_key_exists($i + 1, $keys)) {
1245 $beforekey = $keys[$i + 1];
1248 if (has_capability('mod/lesson:manageoverrides', $PAGE->cm->context)) {
1249 $url = new moodle_url('/mod/lesson/overrides.php', array('cmid' => $PAGE->cm->id));
1250 $node = navigation_node::create(get_string('groupoverrides', 'lesson'),
1251 new moodle_url($url, array('mode' => 'group')),
1252 navigation_node::TYPE_SETTING, null, 'mod_lesson_groupoverrides');
1253 $lessonnode->add_node($node, $beforekey);
1255 $node = navigation_node::create(get_string('useroverrides', 'lesson'),
1256 new moodle_url($url, array('mode' => 'user')),
1257 navigation_node::TYPE_SETTING, null, 'mod_lesson_useroverrides');
1258 $lessonnode->add_node($node, $beforekey);
1261 if (has_capability('mod/lesson:edit', $PAGE->cm->context)) {
1262 $url = new moodle_url('/mod/lesson/view.php', array('id' => $PAGE->cm->id));
1263 $lessonnode->add(get_string('preview', 'lesson'), $url);
1264 $editnode = $lessonnode->add(get_string('edit', 'lesson'));
1265 $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'collapsed'));
1266 $editnode->add(get_string('collapsed', 'lesson'), $url);
1267 $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'full'));
1268 $editnode->add(get_string('full', 'lesson'), $url);
1271 if (has_capability('mod/lesson:viewreports', $PAGE->cm->context)) {
1272 $reportsnode = $lessonnode->add(get_string('reports', 'lesson'));
1273 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportoverview'));
1274 $reportsnode->add(get_string('overview', 'lesson'), $url);
1275 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportdetail'));
1276 $reportsnode->add(get_string('detailedstats', 'lesson'), $url);
1279 if (has_capability('mod/lesson:grade', $PAGE->cm->context)) {
1280 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm->id));
1281 $lessonnode->add(get_string('manualgrading', 'lesson'), $url);
1287 * Get list of available import or export formats
1289 * Copied and modified from lib/questionlib.php
1291 * @param string $type 'import' if import list, otherwise export list assumed
1292 * @return array sorted list of import/export formats available
1294 function lesson_get_import_export_formats($type) {
1295 global $CFG;
1296 $fileformats = core_component::get_plugin_list("qformat");
1298 $fileformatname=array();
1299 foreach ($fileformats as $fileformat=>$fdir) {
1300 $format_file = "$fdir/format.php";
1301 if (file_exists($format_file) ) {
1302 require_once($format_file);
1303 } else {
1304 continue;
1306 $classname = "qformat_$fileformat";
1307 $format_class = new $classname();
1308 if ($type=='import') {
1309 $provided = $format_class->provide_import();
1310 } else {
1311 $provided = $format_class->provide_export();
1313 if ($provided) {
1314 $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat);
1317 natcasesort($fileformatnames);
1319 return $fileformatnames;
1323 * Serves the lesson attachments. Implements needed access control ;-)
1325 * @package mod_lesson
1326 * @category files
1327 * @param stdClass $course course object
1328 * @param stdClass $cm course module object
1329 * @param stdClass $context context object
1330 * @param string $filearea file area
1331 * @param array $args extra arguments
1332 * @param bool $forcedownload whether or not force download
1333 * @param array $options additional options affecting the file serving
1334 * @return bool false if file not found, does not return if found - justsend the file
1336 function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1337 global $CFG, $DB;
1339 if ($context->contextlevel != CONTEXT_MODULE) {
1340 return false;
1343 $fileareas = lesson_get_file_areas();
1344 if (!array_key_exists($filearea, $fileareas)) {
1345 return false;
1348 if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance))) {
1349 return false;
1352 require_course_login($course, true, $cm);
1354 if ($filearea === 'page_contents') {
1355 $pageid = (int)array_shift($args);
1356 if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) {
1357 return false;
1359 $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args);
1361 } else if ($filearea === 'page_answers' || $filearea === 'page_responses') {
1362 $itemid = (int)array_shift($args);
1363 if (!$pageanswers = $DB->get_record('lesson_answers', array('id' => $itemid))) {
1364 return false;
1366 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1368 } else if ($filearea === 'essay_responses') {
1369 $itemid = (int)array_shift($args);
1370 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $itemid))) {
1371 return false;
1373 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1375 } else if ($filearea === 'mediafile') {
1376 if (count($args) > 1) {
1377 // Remove the itemid when it appears to be part of the arguments. If there is only one argument
1378 // then it is surely the file name. The itemid is sometimes used to prevent browser caching.
1379 array_shift($args);
1381 $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args);
1383 } else {
1384 return false;
1387 $fs = get_file_storage();
1388 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1389 return false;
1392 // finally send the file
1393 send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security!
1397 * Returns an array of file areas
1399 * @package mod_lesson
1400 * @category files
1401 * @return array a list of available file areas
1403 function lesson_get_file_areas() {
1404 $areas = array();
1405 $areas['page_contents'] = get_string('pagecontents', 'mod_lesson');
1406 $areas['mediafile'] = get_string('mediafile', 'mod_lesson');
1407 $areas['page_answers'] = get_string('pageanswers', 'mod_lesson');
1408 $areas['page_responses'] = get_string('pageresponses', 'mod_lesson');
1409 $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson');
1410 return $areas;
1414 * Returns a file_info_stored object for the file being requested here
1416 * @package mod_lesson
1417 * @category files
1418 * @global stdClass $CFG
1419 * @param file_browse $browser file browser instance
1420 * @param array $areas file areas
1421 * @param stdClass $course course object
1422 * @param stdClass $cm course module object
1423 * @param stdClass $context context object
1424 * @param string $filearea file area
1425 * @param int $itemid item ID
1426 * @param string $filepath file path
1427 * @param string $filename file name
1428 * @return file_info_stored
1430 function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
1431 global $CFG, $DB;
1433 if (!has_capability('moodle/course:managefiles', $context)) {
1434 // No peaking here for students!
1435 return null;
1438 // Mediafile area does not have sub directories, so let's select the default itemid to prevent
1439 // the user from selecting a directory to access the mediafile content.
1440 if ($filearea == 'mediafile' && is_null($itemid)) {
1441 $itemid = 0;
1444 if (is_null($itemid)) {
1445 return new mod_lesson_file_info($browser, $course, $cm, $context, $areas, $filearea);
1448 $fs = get_file_storage();
1449 $filepath = is_null($filepath) ? '/' : $filepath;
1450 $filename = is_null($filename) ? '.' : $filename;
1451 if (!$storedfile = $fs->get_file($context->id, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) {
1452 return null;
1455 $itemname = $filearea;
1456 if ($filearea == 'page_contents') {
1457 $itemname = $DB->get_field('lesson_pages', 'title', array('lessonid' => $cm->instance, 'id' => $itemid));
1458 $itemname = format_string($itemname, true, array('context' => $context));
1459 } else {
1460 $areas = lesson_get_file_areas();
1461 if (isset($areas[$filearea])) {
1462 $itemname = $areas[$filearea];
1466 $urlbase = $CFG->wwwroot . '/pluginfile.php';
1467 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false);
1472 * Return a list of page types
1473 * @param string $pagetype current page type
1474 * @param stdClass $parentcontext Block's parent context
1475 * @param stdClass $currentcontext Current context of block
1477 function lesson_page_type_list($pagetype, $parentcontext, $currentcontext) {
1478 $module_pagetype = array(
1479 'mod-lesson-*'=>get_string('page-mod-lesson-x', 'lesson'),
1480 'mod-lesson-view'=>get_string('page-mod-lesson-view', 'lesson'),
1481 'mod-lesson-edit'=>get_string('page-mod-lesson-edit', 'lesson'));
1482 return $module_pagetype;
1486 * Update the lesson activity to include any file
1487 * that was uploaded, or if there is none, set the
1488 * mediafile field to blank.
1490 * @param int $lessonid the lesson id
1491 * @param stdClass $context the context
1492 * @param int $draftitemid the draft item
1494 function lesson_update_media_file($lessonid, $context, $draftitemid) {
1495 global $DB;
1497 // Set the filestorage object.
1498 $fs = get_file_storage();
1499 // Save the file if it exists that is currently in the draft area.
1500 file_save_draft_area_files($draftitemid, $context->id, 'mod_lesson', 'mediafile', 0);
1501 // Get the file if it exists.
1502 $files = $fs->get_area_files($context->id, 'mod_lesson', 'mediafile', 0, 'itemid, filepath, filename', false);
1503 // Check that there is a file to process.
1504 if (count($files) == 1) {
1505 // Get the first (and only) file.
1506 $file = reset($files);
1507 // Set the mediafile column in the lessons table.
1508 $DB->set_field('lesson', 'mediafile', '/' . $file->get_filename(), array('id' => $lessonid));
1509 } else {
1510 // Set the mediafile column in the lessons table.
1511 $DB->set_field('lesson', 'mediafile', '', array('id' => $lessonid));
1516 * Get icon mapping for font-awesome.
1518 function mod_lesson_get_fontawesome_icon_map() {
1519 return [
1520 'mod_lesson:e/copy' => 'fa-clone',
1525 * Check if the module has any update that affects the current user since a given time.
1527 * @param cm_info $cm course module data
1528 * @param int $from the time to check updates from
1529 * @param array $filter if we need to check only specific updates
1530 * @return stdClass an object with the different type of areas indicating if they were updated or not
1531 * @since Moodle 3.3
1533 function lesson_check_updates_since(cm_info $cm, $from, $filter = array()) {
1534 global $DB, $USER;
1536 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1538 // Check if there are new pages or answers in the lesson.
1539 $updates->pages = (object) array('updated' => false);
1540 $updates->answers = (object) array('updated' => false);
1541 $select = 'lessonid = ? AND (timecreated > ? OR timemodified > ?)';
1542 $params = array($cm->instance, $from, $from);
1544 $pages = $DB->get_records_select('lesson_pages', $select, $params, '', 'id');
1545 if (!empty($pages)) {
1546 $updates->pages->updated = true;
1547 $updates->pages->itemids = array_keys($pages);
1549 $answers = $DB->get_records_select('lesson_answers', $select, $params, '', 'id');
1550 if (!empty($answers)) {
1551 $updates->answers->updated = true;
1552 $updates->answers->itemids = array_keys($answers);
1555 // Check for new question attempts, grades, pages viewed and timers.
1556 $updates->questionattempts = (object) array('updated' => false);
1557 $updates->grades = (object) array('updated' => false);
1558 $updates->pagesviewed = (object) array('updated' => false);
1559 $updates->timers = (object) array('updated' => false);
1561 $select = 'lessonid = ? AND userid = ? AND timeseen > ?';
1562 $params = array($cm->instance, $USER->id, $from);
1564 $questionattempts = $DB->get_records_select('lesson_attempts', $select, $params, '', 'id');
1565 if (!empty($questionattempts)) {
1566 $updates->questionattempts->updated = true;
1567 $updates->questionattempts->itemids = array_keys($questionattempts);
1569 $pagesviewed = $DB->get_records_select('lesson_branch', $select, $params, '', 'id');
1570 if (!empty($pagesviewed)) {
1571 $updates->pagesviewed->updated = true;
1572 $updates->pagesviewed->itemids = array_keys($pagesviewed);
1575 $select = 'lessonid = ? AND userid = ? AND completed > ?';
1576 $grades = $DB->get_records_select('lesson_grades', $select, $params, '', 'id');
1577 if (!empty($grades)) {
1578 $updates->grades->updated = true;
1579 $updates->grades->itemids = array_keys($grades);
1582 $select = 'lessonid = ? AND userid = ? AND (starttime > ? OR lessontime > ? OR timemodifiedoffline > ?)';
1583 $params = array($cm->instance, $USER->id, $from, $from, $from);
1584 $timers = $DB->get_records_select('lesson_timer', $select, $params, '', 'id');
1585 if (!empty($timers)) {
1586 $updates->timers->updated = true;
1587 $updates->timers->itemids = array_keys($timers);
1590 // Now, teachers should see other students updates.
1591 if (has_capability('mod/lesson:viewreports', $cm->context)) {
1592 $select = 'lessonid = ? AND timeseen > ?';
1593 $params = array($cm->instance, $from);
1595 $insql = '';
1596 $inparams = [];
1597 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1598 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1599 if (empty($groupusers)) {
1600 return $updates;
1602 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1603 $select .= ' AND userid ' . $insql;
1604 $params = array_merge($params, $inparams);
1607 $updates->userquestionattempts = (object) array('updated' => false);
1608 $updates->usergrades = (object) array('updated' => false);
1609 $updates->userpagesviewed = (object) array('updated' => false);
1610 $updates->usertimers = (object) array('updated' => false);
1612 $questionattempts = $DB->get_records_select('lesson_attempts', $select, $params, '', 'id');
1613 if (!empty($questionattempts)) {
1614 $updates->userquestionattempts->updated = true;
1615 $updates->userquestionattempts->itemids = array_keys($questionattempts);
1617 $pagesviewed = $DB->get_records_select('lesson_branch', $select, $params, '', 'id');
1618 if (!empty($pagesviewed)) {
1619 $updates->userpagesviewed->updated = true;
1620 $updates->userpagesviewed->itemids = array_keys($pagesviewed);
1623 $select = 'lessonid = ? AND completed > ?';
1624 if (!empty($insql)) {
1625 $select .= ' AND userid ' . $insql;
1627 $grades = $DB->get_records_select('lesson_grades', $select, $params, '', 'id');
1628 if (!empty($grades)) {
1629 $updates->usergrades->updated = true;
1630 $updates->usergrades->itemids = array_keys($grades);
1633 $select = 'lessonid = ? AND (starttime > ? OR lessontime > ? OR timemodifiedoffline > ?)';
1634 $params = array($cm->instance, $from, $from, $from);
1635 if (!empty($insql)) {
1636 $select .= ' AND userid ' . $insql;
1637 $params = array_merge($params, $inparams);
1639 $timers = $DB->get_records_select('lesson_timer', $select, $params, '', 'id');
1640 if (!empty($timers)) {
1641 $updates->usertimers->updated = true;
1642 $updates->usertimers->itemids = array_keys($timers);
1645 return $updates;
1649 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1651 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1652 * is not displayed on the block.
1654 * @param calendar_event $event
1655 * @param \core_calendar\action_factory $factory
1656 * @return \core_calendar\local\event\entities\action_interface|null
1658 function mod_lesson_core_calendar_provide_event_action(calendar_event $event,
1659 \core_calendar\action_factory $factory) {
1660 global $DB, $CFG, $USER;
1661 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
1663 $cm = get_fast_modinfo($event->courseid)->instances['lesson'][$event->instance];
1664 $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST));
1666 if ($lesson->count_user_retries($USER->id)) {
1667 // If the user has attempted the lesson then there is no further action for the user.
1668 return null;
1671 // Apply overrides.
1672 $lesson->update_effective_access($USER->id);
1674 return $factory->create_instance(
1675 get_string('startlesson', 'lesson'),
1676 new \moodle_url('/mod/lesson/view.php', ['id' => $cm->id]),
1678 $lesson->is_accessible()
1683 * Add a get_coursemodule_info function in case any lesson type wants to add 'extra' information
1684 * for the course (see resource).
1686 * Given a course_module object, this function returns any "extra" information that may be needed
1687 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1689 * @param stdClass $coursemodule The coursemodule object (record).
1690 * @return cached_cm_info An object on information that the courses
1691 * will know about (most noticeably, an icon).
1693 function lesson_get_coursemodule_info($coursemodule) {
1694 global $DB;
1696 $dbparams = ['id' => $coursemodule->instance];
1697 $fields = 'id, name, intro, introformat, completionendreached, completiontimespent';
1698 if (!$lesson = $DB->get_record('lesson', $dbparams, $fields)) {
1699 return false;
1702 $result = new cached_cm_info();
1703 $result->name = $lesson->name;
1705 if ($coursemodule->showdescription) {
1706 // Convert intro to html. Do not filter cached version, filters run at display time.
1707 $result->content = format_module_intro('lesson', $lesson, $coursemodule->id, false);
1710 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1711 if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
1712 $result->customdata['customcompletionrules']['completionendreached'] = $lesson->completionendreached;
1713 $result->customdata['customcompletionrules']['completiontimespent'] = $lesson->completiontimespent;
1716 return $result;
1720 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1722 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1723 * @return array $descriptions the array of descriptions for the custom rules.
1725 function mod_lesson_get_completion_active_rule_descriptions($cm) {
1726 // Values will be present in cm_info, and we assume these are up to date.
1727 if (empty($cm->customdata['customcompletionrules'])
1728 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1729 return [];
1732 $descriptions = [];
1733 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1734 switch ($key) {
1735 case 'completionendreached':
1736 if (empty($val)) {
1737 continue;
1739 $descriptions[] = get_string('completionendreached_desc', 'lesson', $val);
1740 break;
1741 case 'completiontimespent':
1742 if (empty($val)) {
1743 continue;
1745 $descriptions[] = get_string('completiontimespentdesc', 'lesson', format_time($val));
1746 break;
1747 default:
1748 break;
1751 return $descriptions;
1755 * This function calculates the minimum and maximum cutoff values for the timestart of
1756 * the given event.
1758 * It will return an array with two values, the first being the minimum cutoff value and
1759 * the second being the maximum cutoff value. Either or both values can be null, which
1760 * indicates there is no minimum or maximum, respectively.
1762 * If a cutoff is required then the function must return an array containing the cutoff
1763 * timestamp and error string to display to the user if the cutoff value is violated.
1765 * A minimum and maximum cutoff return value will look like:
1767 * [1505704373, 'The due date must be after the start date'],
1768 * [1506741172, 'The due date must be before the cutoff date']
1771 * @param calendar_event $event The calendar event to get the time range for
1772 * @param stdClass $instance The module instance to get the range from
1773 * @return array
1775 function mod_lesson_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1776 $mindate = null;
1777 $maxdate = null;
1779 if ($event->eventtype == LESSON_EVENT_TYPE_OPEN) {
1780 // The start time of the open event can't be equal to or after the
1781 // close time of the lesson activity.
1782 if (!empty($instance->deadline)) {
1783 $maxdate = [
1784 $instance->deadline,
1785 get_string('openafterclose', 'lesson')
1788 } else if ($event->eventtype == LESSON_EVENT_TYPE_CLOSE) {
1789 // The start time of the close event can't be equal to or earlier than the
1790 // open time of the lesson activity.
1791 if (!empty($instance->available)) {
1792 $mindate = [
1793 $instance->available,
1794 get_string('closebeforeopen', 'lesson')
1799 return [$mindate, $maxdate];
1803 * This function will update the lesson module according to the
1804 * event that has been modified.
1806 * It will set the available or deadline value of the lesson instance
1807 * according to the type of event provided.
1809 * @throws \moodle_exception
1810 * @param \calendar_event $event
1811 * @param stdClass $lesson The module instance to get the range from
1813 function mod_lesson_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $lesson) {
1814 global $DB;
1816 if (empty($event->instance) || $event->modulename != 'lesson') {
1817 return;
1820 if ($event->instance != $lesson->id) {
1821 return;
1824 if (!in_array($event->eventtype, [LESSON_EVENT_TYPE_OPEN, LESSON_EVENT_TYPE_CLOSE])) {
1825 return;
1828 $courseid = $event->courseid;
1829 $modulename = $event->modulename;
1830 $instanceid = $event->instance;
1831 $modified = false;
1833 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1834 $context = context_module::instance($coursemodule->id);
1836 // The user does not have the capability to modify this activity.
1837 if (!has_capability('moodle/course:manageactivities', $context)) {
1838 return;
1841 if ($event->eventtype == LESSON_EVENT_TYPE_OPEN) {
1842 // If the event is for the lesson activity opening then we should
1843 // set the start time of the lesson activity to be the new start
1844 // time of the event.
1845 if ($lesson->available != $event->timestart) {
1846 $lesson->available = $event->timestart;
1847 $lesson->timemodified = time();
1848 $modified = true;
1850 } else if ($event->eventtype == LESSON_EVENT_TYPE_CLOSE) {
1851 // If the event is for the lesson activity closing then we should
1852 // set the end time of the lesson activity to be the new start
1853 // time of the event.
1854 if ($lesson->deadline != $event->timestart) {
1855 $lesson->deadline = $event->timestart;
1856 $modified = true;
1860 if ($modified) {
1861 $lesson->timemodified = time();
1862 $DB->update_record('lesson', $lesson);
1863 $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1864 $event->trigger();