MDL-60072 mod_lesson: Add missing name attribute
[moodle.git] / mod / lesson / lib.php
CommitLineData
8cc86111 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
5491947a 18/**
19 * Standard library of functions and constants for lesson
20 *
9b24f68b 21 * @package mod_lesson
8d1a3963 22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
cc3dbaaa 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5491947a 24 **/
97c44107 25
28f5bf67
PS
26defined('MOODLE_INTERNAL') || die();
27
1e7f8ea2 28/* Do not include any libraries here! */
97c44107 29
acf85537 30/**
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.
35 *
8cc86111 36 * @global object
37 * @global object
acf85537 38 * @param object $lesson Lesson post data from the form
39 * @return int
40 **/
0a4abb73 41function lesson_add_instance($data, $mform) {
1e7f8ea2 42 global $DB;
bbcbc0fe 43
0a4abb73 44 $cmid = $data->coursemodule;
684c3be7
MN
45 $draftitemid = $data->mediafile;
46 $context = context_module::instance($cmid);
5f649aaa 47
0a4abb73 48 lesson_process_pre_save($data);
271fea97 49
0a4abb73
SH
50 unset($data->mediafile);
51 $lessonid = $DB->insert_record("lesson", $data);
52 $data->id = $lessonid;
97c44107 53
684c3be7 54 lesson_update_media_file($lessonid, $context, $draftitemid);
0a4abb73
SH
55
56 lesson_process_post_save($data);
57
58 lesson_grade_item_update($data);
92bcca38 59
b5914b61 60 return $lessonid;
bbcbc0fe 61}
62
acf85537 63/**
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.
67 *
8cc86111 68 * @global object
acf85537 69 * @param object $lesson Lesson post data from the form
70 * @return boolean
71 **/
0a4abb73 72function lesson_update_instance($data, $mform) {
c18269c7 73 global $DB;
bbcbc0fe 74
0a4abb73
SH
75 $data->id = $data->instance;
76 $cmid = $data->coursemodule;
684c3be7
MN
77 $draftitemid = $data->mediafile;
78 $context = context_module::instance($cmid);
1535c81b 79
0a4abb73 80 lesson_process_pre_save($data);
97c44107 81
0a4abb73 82 unset($data->mediafile);
1e7f8ea2 83 $DB->update_record("lesson", $data);
97c44107 84
684c3be7 85 lesson_update_media_file($data->id, $context, $draftitemid);
0a4abb73
SH
86
87 lesson_process_post_save($data);
92bcca38 88
89 // update grade item definition
0a4abb73 90 lesson_grade_item_update($data);
92bcca38 91
92 // update grades - TODO: do it only when grading style changes
0a4abb73 93 lesson_update_grades($data, 0, false);
92bcca38 94
1e7f8ea2 95 return true;
bbcbc0fe 96}
97
e0e1a83e
JMV
98/**
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.
102 *
103 * @uses LESSON_MAX_EVENT_LENGTH
104 * @param object $lesson the lesson object.
105 * @param object $override (optional) limit to a specific override
106 */
107function lesson_update_events($lesson, $override = null) {
108 global $CFG, $DB;
109
9ff8cdd9 110 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
e0e1a83e
JMV
111 require_once($CFG->dirroot . '/calendar/lib.php');
112
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;
120 } else {
121 $conds['groupid'] = $override->groupid;
122 }
123 }
8dada7e3 124 $oldevents = $DB->get_records('event', $conds, 'id ASC');
e0e1a83e 125
98239b2d 126 // Now make a to-do list of all that needs to be updated.
e0e1a83e 127 if (empty($override)) {
98239b2d 128 // We are updating the primary settings for the lesson, so we need to add all the overrides.
8dada7e3
CB
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());
e0e1a83e
JMV
135 } else {
136 // Just do the one override.
137 $overrides = array($override);
138 }
139
98239b2d
JP
140 // Get group override priorities.
141 $grouppriorities = lesson_get_group_override_priorities($lesson->id);
142
e0e1a83e
JMV
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;
148
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);
152
153 if (!empty($lesson->coursemodule)) {
154 $cmid = $lesson->coursemodule;
155 } else {
156 $cmid = get_coursemodule_from_instance('lesson', $lesson->id, $lesson->course)->id;
157 }
158
159 $event = new stdClass();
8a8bd425 160 $event->type = !$deadline ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
e0e1a83e
JMV
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);
8a8bd425 170 $event->timesort = $available;
e0e1a83e 171 $event->visible = instance_is_visible('lesson', $lesson);
8a8bd425 172 $event->eventtype = LESSON_EVENT_TYPE_OPEN;
8dada7e3 173 $event->priority = null;
e0e1a83e 174
98239b2d 175 // Determine the event name and priority.
e0e1a83e 176 if ($groupid) {
98239b2d 177 // Group override event.
e0e1a83e
JMV
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.
183 continue;
184 }
185 $eventname = get_string('overridegroupeventname', 'lesson', $params);
98239b2d
JP
186 // Set group override priority.
187 if ($grouppriorities !== null) {
188 $openpriorities = $grouppriorities['open'];
189 if (isset($openpriorities[$available])) {
190 $event->priority = $openpriorities[$available];
191 }
192 }
e0e1a83e 193 } else if ($userid) {
98239b2d 194 // User override event.
e0e1a83e
JMV
195 $params = new stdClass();
196 $params->lesson = $lesson->name;
197 $eventname = get_string('overrideusereventname', 'lesson', $params);
98239b2d
JP
198 // Set user override priority.
199 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
e0e1a83e 200 } else {
98239b2d 201 // The parent event.
e0e1a83e
JMV
202 $eventname = $lesson->name;
203 }
98239b2d 204
e0e1a83e 205 if ($addopen or $addclose) {
98239b2d
JP
206 // Separate start and end events.
207 $event->timeduration = 0;
208 if ($available && $addopen) {
e0e1a83e
JMV
209 if ($oldevent = array_shift($oldevents)) {
210 $event->id = $oldevent->id;
211 } else {
212 unset($event->id);
213 }
f10721d6 214 $event->name = get_string('lessoneventopens', 'lesson', $eventname);
e0e1a83e
JMV
215 // The method calendar_event::create will reuse a db record if the id field is set.
216 calendar_event::create($event);
98239b2d
JP
217 }
218 if ($deadline && $addclose) {
219 if ($oldevent = array_shift($oldevents)) {
220 $event->id = $oldevent->id;
221 } else {
222 unset($event->id);
e0e1a83e 223 }
8a8bd425 224 $event->type = CALENDAR_EVENT_TYPE_ACTION;
fac50516 225 $event->name = get_string('lessoneventcloses', 'lesson', $eventname);
98239b2d 226 $event->timestart = $deadline;
8a8bd425
CB
227 $event->timesort = $deadline;
228 $event->eventtype = LESSON_EVENT_TYPE_CLOSE;
98239b2d
JP
229 if ($groupid && $grouppriorities !== null) {
230 $closepriorities = $grouppriorities['close'];
231 if (isset($closepriorities[$deadline])) {
232 $event->priority = $closepriorities[$deadline];
e0e1a83e 233 }
e0e1a83e 234 }
98239b2d 235 calendar_event::create($event);
e0e1a83e
JMV
236 }
237 }
238 }
239
240 // Delete any leftover events.
241 foreach ($oldevents as $badevent) {
242 $badevent = calendar_event::load($badevent);
243 $badevent->delete();
244 }
245}
246
efe24976
JP
247/**
248 * Calculates the priorities of timeopen and timeclose values for group overrides for a lesson.
249 *
756a132f 250 * @param int $lessonid The lesson ID.
efe24976
JP
251 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
252 */
253function lesson_get_group_override_priorities($lessonid) {
254 global $DB;
255
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');
260 if (!$overrides) {
261 return null;
262 }
263
264 $grouptimeopen = [];
265 $grouptimeclose = [];
266 foreach ($overrides as $override) {
267 if ($override->available !== null && !in_array($override->available, $grouptimeopen)) {
268 $grouptimeopen[] = $override->available;
269 }
270 if ($override->deadline !== null && !in_array($override->deadline, $grouptimeclose)) {
271 $grouptimeclose[] = $override->deadline;
272 }
273 }
274
756a132f
CB
275 // Sort open times in ascending manner. The earlier open time gets higher priority.
276 sort($grouptimeopen);
efe24976
JP
277 // Set priorities.
278 $opengrouppriorities = [];
279 $openpriority = 1;
280 foreach ($grouptimeopen as $timeopen) {
281 $opengrouppriorities[$timeopen] = $openpriority++;
282 }
283
756a132f
CB
284 // Sort close times in descending manner. The later close time gets higher priority.
285 rsort($grouptimeclose);
efe24976
JP
286 // Set priorities.
287 $closegrouppriorities = [];
288 $closepriority = 1;
289 foreach ($grouptimeclose as $timeclose) {
290 $closegrouppriorities[$timeclose] = $closepriority++;
291 }
292
293 return [
294 'open' => $opengrouppriorities,
295 'close' => $closegrouppriorities
296 ];
297}
298
e0e1a83e
JMV
299/**
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()
305 *
306 * @param int $courseid
9ffbdafc
AG
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).
e0e1a83e
JMV
309 * @return bool
310 */
9ffbdafc 311function lesson_refresh_events($courseid = 0, $instance = null, $cm = null) {
e0e1a83e
JMV
312 global $DB;
313
9ffbdafc
AG
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);
318 }
319 lesson_update_events($instance);
320 return true;
321 }
322
e0e1a83e 323 if ($courseid == 0) {
2b9d9740 324 if (!$lessons = $DB->get_records('lesson')) {
e0e1a83e
JMV
325 return true;
326 }
327 } else {
328 if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) {
329 return true;
330 }
331 }
332
333 foreach ($lessons as $lesson) {
334 lesson_update_events($lesson);
335 }
336
337 return true;
338}
bbcbc0fe 339
8cc86111 340/**
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.
344 *
345 * @global object
346 * @param int $id
347 * @return bool
348 */
bbcbc0fe 349function lesson_delete_instance($id) {
3d53d99e
PS
350 global $DB, $CFG;
351 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
352
0a4abb73
SH
353 $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST);
354 $lesson = new lesson($lesson);
355 return $lesson->delete();
bbcbc0fe 356}
357
8cc86111 358/**
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
364 *
365 * @global object
366 * @param object $course
367 * @param object $user
368 * @param object $mod
369 * @param object $lesson
370 * @return object
371 */
bbcbc0fe 372function lesson_user_outline($course, $user, $mod, $lesson) {
fbf85b8d 373 global $CFG, $DB;
df0442c6 374
1a96363a
NC
375 require_once("$CFG->libdir/gradelib.php");
376 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
39790bd8 377 $return = new stdClass();
fbf85b8d 378
1a96363a 379 if (empty($grades->items[0]->grades)) {
fbf85b8d 380 $return->info = get_string("nolessonattempts", "lesson");
bbcbc0fe 381 } else {
1a96363a 382 $grade = reset($grades->items[0]->grades);
fbf85b8d
SB
383 if (empty($grade->grade)) {
384
385 // Check to see if it an ungraded / incomplete attempt.
386 $sql = "SELECT *
387 FROM {lesson_timer}
388 WHERE lessonid = :lessonid
389 AND userid = :userid
390 ORDER BY starttime DESC";
391 $params = array('lessonid' => $lesson->id, 'userid' => $user->id);
392
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");
397 } else {
398 $return->info = get_string("notyetcompleted", "lesson");
399 }
400 $return->time = $attempt->lessontime;
401 } else {
402 $return->info = get_string("nolessonattempts", "lesson");
403 }
4433f871 404 } else {
fbf85b8d
SB
405 $return->info = get_string("grade") . ': ' . $grade->str_long_grade;
406
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;
412 } else {
413 $return->time = $grade->datesubmitted;
414 }
4433f871 415 }
bbcbc0fe 416 }
417 return $return;
418}
419
8cc86111 420/**
421 * Print a detailed representation of what a user has done with
422 * a given particular instance of this module, for user activity reports.
423 *
424 * @global object
425 * @param object $course
426 * @param object $user
427 * @param object $mod
428 * @param object $lesson
429 * @return bool
430 */
bbcbc0fe 431function lesson_user_complete($course, $user, $mod, $lesson) {
1a96363a
NC
432 global $DB, $OUTPUT, $CFG;
433
434 require_once("$CFG->libdir/gradelib.php");
435
436 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
764c4fbc
SB
437
438 // Display the grade and feedback.
439 if (empty($grades->items[0]->grades)) {
440 echo $OUTPUT->container(get_string("nolessonattempts", "lesson"));
441 } else {
1a96363a 442 $grade = reset($grades->items[0]->grades);
764c4fbc
SB
443 if (empty($grade->grade)) {
444 // Check to see if it an ungraded / incomplete attempt.
445 $sql = "SELECT *
446 FROM {lesson_timer}
447 WHERE lessonid = :lessonid
448 AND userid = :userid
449 ORDER by starttime desc";
450 $params = array('lessonid' => $lesson->id, 'userid' => $user->id);
451
452 if ($attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE)) {
453 if ($attempt->completed) {
454 $status = get_string("completed", "lesson");
455 } else {
456 $status = get_string("notyetcompleted", "lesson");
457 }
458 } else {
459 $status = get_string("nolessonattempts", "lesson");
460 }
461 } else {
462 $status = get_string("grade") . ': ' . $grade->str_long_grade;
463 }
464
465 // Display the grade or lesson status if there isn't one.
466 echo $OUTPUT->container($status);
467
1a96363a
NC
468 if ($grade->str_feedback) {
469 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
470 }
471 }
fe75e76b 472
764c4fbc
SB
473 // Display the lesson progress.
474 // Attempt, pages viewed, questions answered, correct answers, time.
646fc290 475 $params = array ("lessonid" => $lesson->id, "userid" => $user->id);
764c4fbc
SB
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)) {
d68ccdba 479 echo $OUTPUT->box_start();
3ab269ed 480 $table = new html_table();
764c4fbc
SB
481 // Table Headings.
482 $table->head = array (get_string("attemptheader", "lesson"),
483 get_string("totalpagesviewedheader", "lesson"),
484 get_string("numberofpagesviewedheader", "lesson"),
485 get_string("numberofcorrectanswersheader", "lesson"),
486 get_string("time"));
ac8e16be 487 $table->width = "100%";
764c4fbc
SB
488 $table->align = array ("center", "center", "center", "center", "center");
489 $table->size = array ("*", "*", "*", "*", "*");
ac8e16be 490 $table->cellpadding = 2;
491 $table->cellspacing = 0;
bbcbc0fe 492
493 $retry = 0;
764c4fbc 494 $nquestions = 0;
bbcbc0fe 495 $npages = 0;
496 $ncorrect = 0;
5f649aaa 497
764c4fbc 498 // Filter question pages (from lesson_attempts).
ac8e16be 499 foreach ($attempts as $attempt) {
500 if ($attempt->retry == $retry) {
501 $npages++;
764c4fbc 502 $nquestions++;
bbcbc0fe 503 if ($attempt->correct) {
504 $ncorrect++;
505 }
506 $timeseen = $attempt->timeseen;
507 } else {
764c4fbc 508 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
bbcbc0fe 509 $retry++;
764c4fbc 510 $nquestions = 1;
bbcbc0fe 511 $npages = 1;
512 if ($attempt->correct) {
513 $ncorrect = 1;
514 } else {
515 $ncorrect = 0;
516 }
ac8e16be 517 }
518 }
764c4fbc
SB
519
520 // Filter content pages (from lesson_branch).
521 foreach ($branches as $branch) {
522 if ($branch->retry == $retry) {
523 $npages++;
524
525 $timeseen = $branch->timeseen;
526 } else {
527 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
528 $retry++;
529 $npages = 1;
530 }
531 }
532 if ($npages > 0) {
533 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
bbcbc0fe 534 }
16be8974 535 echo html_writer::table($table);
d68ccdba 536 echo $OUTPUT->box_end();
bbcbc0fe 537 }
538
bbcbc0fe 539 return true;
540}
541
4342dc32 542/**
543 * Prints lesson summaries on MyMoodle Page
544 *
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.
548 *
e9dfeec9 549 * @deprecated since 3.3
063b7ee6 550 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
8cc86111 551 * @global object
552 * @global stdClass
553 * @global object
554 * @uses CONTEXT_MODULE
4342dc32 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 )
8cc86111 557 * @return void
4342dc32 558 */
559function lesson_print_overview($courses, &$htmlarray) {
fe75e76b 560 global $USER, $CFG, $DB, $OUTPUT;
4342dc32 561
e9dfeec9
MN
562 debugging('The function lesson_print_overview() is now deprecated.', DEBUG_DEVELOPER);
563
4342dc32 564 if (!$lessons = get_all_instances_in_courses('lesson', $courses)) {
565 return;
566 }
567
673e0d5a
SB
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
571 FROM {lesson_grades}
572 WHERE userid = ?
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;
578 }
579
580 // Get the current course ID.
581 $listoflessons = array();
582 foreach ($lessons as $lesson) {
583 $listoflessons[] = $lesson->id;
584 }
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);
2c4b43d9
MN
587 $dbparams = array_merge($inparams, array('userid' => $USER->id));
588
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
592 JOIN (
593 SELECT idselect.lessonid, idselect.userid, MAX(idselect.id) AS id
594 FROM {lesson_attempts} idselect
595 JOIN (
596 SELECT lessonid, userid, MAX(timeseen) AS timeseen
597 FROM {lesson_attempts}
598 WHERE userid = :userid
599 AND lessonid $insql
600 GROUP BY userid, lessonid
601 ) timeselect
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
606 ) aid
607 ON l.id = aid.id
608 JOIN {lesson_pages} p
609 ON l.pageid = p.id ";
610 $lastattempts = $DB->get_records_sql($select . $from, $dbparams);
611
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);
673e0d5a
SB
616
617 $lastviewed = array();
618 foreach ($lastattempts as $lastattempt) {
2c4b43d9
MN
619 $lastviewed[$lastattempt->lessonid] = $lastattempt;
620 }
621
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;
673e0d5a
SB
629 }
630 }
631
632 // Since we have lessons in this course, now include the constants we need.
633 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
4342dc32 634
635 $now = time();
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
640
673e0d5a
SB
641 // Visibility.
642 $class = (!$lesson->visible) ? 'dimmed' : '';
4342dc32 643
673e0d5a
SB
644 // Context.
645 $context = context_module::instance($lesson->coursemodule);
4342dc32 646
673e0d5a
SB
647 // Link to activity.
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');
651
652 // Deadline.
fe75e76b 653 $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info');
4342dc32 654
673e0d5a
SB
655 // Attempt information.
656 if (has_capability('mod/lesson:manage', $context)) {
657 // This is a teacher, Get the Number of user attempts.
c1500a82 658 $attempts = $DB->count_records('lesson_grades', array('lessonid' => $lesson->id));
fe75e76b 659 $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info');
673e0d5a 660 $str = $OUTPUT->box($str, 'lesson overview');
4342dc32 661 } else {
673e0d5a
SB
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');
672 } else {
673 // User has completed the lesson and no retakes are allowed.
674 $str = '';
675 }
676
677 } else {
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');
689 } else {
690 // User has completed the lesson and no retakes are allowed.
691 $str = '';
692 }
693
694 } else {
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');
698 }
699
700 } else {
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');
704 }
705 }
706
4342dc32 707 } else {
673e0d5a
SB
708 // User has not yet started this lesson.
709 $str .= $OUTPUT->box(get_string('nolessonattempts', 'lesson'), 'info');
710 $str = $OUTPUT->box($str, 'lesson overview');
4342dc32 711 }
712 }
673e0d5a
SB
713 if (!empty($str)) {
714 if (empty($htmlarray[$lesson->course]['lesson'])) {
715 $htmlarray[$lesson->course]['lesson'] = $str;
716 } else {
717 $htmlarray[$lesson->course]['lesson'] .= $str;
718 }
4342dc32 719 }
720 }
721 }
722}
723
8cc86111 724/**
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 ...
728 * @global stdClass
729 * @return bool true
730 */
bbcbc0fe 731function lesson_cron () {
bbcbc0fe 732 global $CFG;
733
734 return true;
735}
736
92bcca38 737/**
738 * Return grade for given user or all users.
739 *
8cc86111 740 * @global stdClass
741 * @global object
92bcca38 742 * @param int $lessonid id of lesson
743 * @param int $userid optional user id, 0 means all users
8a8bd425 744 * @return array array of grades, false if none
92bcca38 745 */
746function lesson_get_user_grades($lesson, $userid=0) {
646fc290 747 global $CFG, $DB;
bbcbc0fe 748
b920f6e8 749 $params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id);
fe75e76b 750
85c13c69 751 if (!empty($userid)) {
646fc290 752 $params["userid"] = $userid;
b920f6e8 753 $params["userid2"] = $userid;
646fc290 754 $user = "AND u.id = :userid";
b920f6e8 755 $fuser = "AND uu.id = :userid2";
646fc290 756 }
757 else {
e57bc529 758 $user="";
646fc290 759 $fuser="";
760 }
fe75e76b 761
512ce792 762 if ($lesson->retake) {
763 if ($lesson->usemaxgrade) {
ac9b0805 764 $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade
646fc290 765 FROM {user} u, {lesson_grades} g
766 WHERE u.id = g.userid AND g.lessonid = :lessonid
92bcca38 767 $user
768 GROUP BY u.id";
512ce792 769 } else {
ac9b0805 770 $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade
646fc290 771 FROM {user} u, {lesson_grades} g
772 WHERE u.id = g.userid AND g.lessonid = :lessonid
92bcca38 773 $user
774 GROUP BY u.id";
512ce792 775 }
96fa52a4 776 unset($params['lessonid2']);
777 unset($params['userid2']);
512ce792 778 } else {
92bcca38 779 // use only first attempts (with lowest id in lesson_grades table)
780 $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted
646fc290 781 FROM {user} uu, {lesson_grades} gg
b920f6e8 782 WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2
92bcca38 783 $fuser
784 GROUP BY uu.id";
785
ac9b0805 786 $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade
646fc290 787 FROM {user} u, {lesson_grades} g, ($firstonly) f
788 WHERE u.id = g.userid AND g.lessonid = :lessonid
92bcca38 789 AND g.id = f.firstcompleted AND g.userid=f.userid
790 $user";
791 }
792
646fc290 793 return $DB->get_records_sql($sql, $params);
92bcca38 794}
795
796/**
797 * Update grades in central gradebook
798 *
a153c9f2 799 * @category grade
775f811a 800 * @param object $lesson
801 * @param int $userid specific user only, 0 means all
8cc86111 802 * @param bool $nullifnone
92bcca38 803 */
775f811a 804function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
646fc290 805 global $CFG, $DB;
775f811a 806 require_once($CFG->libdir.'/gradelib.php');
92bcca38 807
c7d1a37b 808 if ($lesson->grade == 0 || $lesson->practice) {
775f811a 809 lesson_grade_item_update($lesson);
92bcca38 810
775f811a 811 } else if ($grades = lesson_get_user_grades($lesson, $userid)) {
812 lesson_grade_item_update($lesson, $grades);
eafb9d9e 813
775f811a 814 } else if ($userid and $nullifnone) {
39790bd8 815 $grade = new stdClass();
775f811a 816 $grade->userid = $userid;
ecea65ca 817 $grade->rawgrade = null;
775f811a 818 lesson_grade_item_update($lesson, $grade);
92bcca38 819
820 } else {
775f811a 821 lesson_grade_item_update($lesson);
822 }
823}
824
92bcca38 825/**
826 * Create grade item for given lesson
827 *
a153c9f2 828 * @category grade
8cc86111 829 * @uses GRADE_TYPE_VALUE
830 * @uses GRADE_TYPE_NONE
92bcca38 831 * @param object $lesson object with extra cmidnumber
8cc86111 832 * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
92bcca38 833 * @return int 0 if ok, error code otherwise
834 */
ecea65ca 835function lesson_grade_item_update($lesson, $grades=null) {
92bcca38 836 global $CFG;
837 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
838 require_once($CFG->libdir.'/gradelib.php');
839 }
840
841 if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present
842 $params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber);
ac8e16be 843 } else {
92bcca38 844 $params = array('itemname'=>$lesson->name);
ac8e16be 845 }
92bcca38 846
33ce9e58 847 if (!$lesson->practice and $lesson->grade > 0) {
92bcca38 848 $params['gradetype'] = GRADE_TYPE_VALUE;
91ca18e8 849 $params['grademax'] = $lesson->grade;
92bcca38 850 $params['grademin'] = 0;
33ce9e58 851 } else if (!$lesson->practice and $lesson->grade < 0) {
f51cda3d
AD
852 $params['gradetype'] = GRADE_TYPE_SCALE;
853 $params['scaleid'] = -$lesson->grade;
da7e5daf 854
16c25753
TL
855 // Make sure current grade fetched correctly from $grades
856 $currentgrade = null;
74dd3bd6 857 if (!empty($grades)) {
16c25753
TL
858 if (is_array($grades)) {
859 $currentgrade = reset($grades);
860 } else {
861 $currentgrade = $grades;
862 }
863 }
864
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);
74dd3bd6
TL
868 $params['grademax'] = reset($grade->items)->grademax;
869 }
92bcca38 870 } else {
871 $params['gradetype'] = GRADE_TYPE_NONE;
92bcca38 872 }
873
0b5a80a1 874 if ($grades === 'reset') {
875 $params['reset'] = true;
ecea65ca 876 $grades = null;
13b92708 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);
883 }
884 foreach ($grades as $key => $grade) {
885 if (!is_array($grade)) {
886 $grades[$key] = $grade = (array) $grade;
887 }
76027a9f
AD
888 //check raw grade isnt null otherwise we erroneously insert a grade of 0
889 if ($grade['rawgrade'] !== null) {
da7e5daf 890 $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100);
76027a9f
AD
891 } else {
892 //setting rawgrade to null just in case user is deleting a grade
893 $grades[$key]['rawgrade'] = null;
894 }
13b92708 895 }
0b5a80a1 896 }
897
898 return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params);
92bcca38 899}
900
8cc86111 901/**
b2b4ec30
RT
902 * List the actions that correspond to a view of this module.
903 * This is used by the participation report.
904 *
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.
908 *
8cc86111 909 * @return array
910 */
f3221af9 911function lesson_get_view_actions() {
cf051cc4 912 return array('view','view all');
f3221af9 913}
914
8cc86111 915/**
b2b4ec30
RT
916 * List the actions that correspond to a post of this module.
917 * This is used by the participation report.
918 *
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.
922 *
8cc86111 923 * @return array
924 */
f3221af9 925function lesson_get_post_actions() {
0a4abb73 926 return array('end','start');
f3221af9 927}
928
acf85537 929/**
930 * Runs any processes that must run before
931 * a lesson insert/update
932 *
8cc86111 933 * @global object
acf85537 934 * @param object $lesson Lesson form data
935 * @return void
936 **/
937function lesson_process_pre_save(&$lesson) {
646fc290 938 global $DB;
fe75e76b 939
acf85537 940 $lesson->timemodified = time();
941
a1acc001
JMV
942 if (empty($lesson->timelimit)) {
943 $lesson->timelimit = 0;
862bd9cd 944 }
acf85537 945 if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) {
946 $lesson->timespent = 0;
947 }
948 if (!isset($lesson->completed)) {
949 $lesson->completed = 0;
950 }
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;
955 }
956
0a4abb73
SH
957 if (empty($lesson->width)) {
958 $lesson->width = 640;
959 }
960 if (empty($lesson->height)) {
961 $lesson->height = 480;
962 }
963 if (empty($lesson->bgcolor)) {
964 $lesson->bgcolor = '#FFFFFF';
965 }
966
acf85537 967 // Conditions for dependency
968 $conditions = new stdClass;
969 $conditions->timespent = $lesson->timespent;
970 $conditions->completed = $lesson->completed;
971 $conditions->gradebetterthan = $lesson->gradebetterthan;
646fc290 972 $lesson->conditions = serialize($conditions);
acf85537 973 unset($lesson->timespent);
974 unset($lesson->completed);
975 unset($lesson->gradebetterthan);
976
4d22ec81 977 if (empty($lesson->password)) {
acf85537 978 unset($lesson->password);
979 }
acf85537 980}
981
982/**
983 * Runs any processes that must be run
984 * after a lesson insert/update
985 *
8cc86111 986 * @global object
acf85537 987 * @param object $lesson Lesson form data
988 * @return void
989 **/
990function lesson_process_post_save(&$lesson) {
e0e1a83e
JMV
991 // Update the events relating to this lesson.
992 lesson_update_events($lesson);
9ffbdafc
AG
993 $completionexpected = (!empty($lesson->completionexpected)) ? $lesson->completionexpected : null;
994 \core_completion\api::update_completion_date_event($lesson->coursemodule, 'lesson', $lesson, $completionexpected);
acf85537 995}
996
0b5a80a1 997
998/**
999 * Implementation of the function for printing the form elements that control
1000 * whether the course reset functionality affects the lesson.
fe75e76b 1001 *
0b5a80a1 1002 * @param $mform form passed by reference
1003 */
1004function 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'));
e0e1a83e
JMV
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'));
0b5a80a1 1011}
1012
1013/**
1014 * Course reset form defaults.
8cc86111 1015 * @param object $course
1016 * @return array
0b5a80a1 1017 */
1018function lesson_reset_course_form_defaults($course) {
e0e1a83e
JMV
1019 return array('reset_lesson' => 1,
1020 'reset_lesson_group_overrides' => 1,
1021 'reset_lesson_user_overrides' => 1);
0b5a80a1 1022}
1023
1024/**
1025 * Removes all grades from gradebook
8cc86111 1026 *
1027 * @global stdClass
1028 * @global object
0b5a80a1 1029 * @param int $courseid
1030 * @param string optional type
1031 */
1032function lesson_reset_gradebook($courseid, $type='') {
646fc290 1033 global $CFG, $DB;
0b5a80a1 1034
1035 $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
646fc290 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)) {
0b5a80a1 1040 foreach ($lessons as $lesson) {
1041 lesson_grade_item_update($lesson, 'reset');
1042 }
1043 }
1044}
1045
1046/**
72d2982e 1047 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 1048 * lesson attempts for course $data->courseid.
8cc86111 1049 *
1050 * @global stdClass
1051 * @global object
1052 * @param object $data the data submitted from the reset course.
0b5a80a1 1053 * @return array status array
1054 */
1055function lesson_reset_userdata($data) {
646fc290 1056 global $CFG, $DB;
0b5a80a1 1057
1058 $componentstr = get_string('modulenameplural', 'lesson');
1059 $status = array();
1060
1061 if (!empty($data->reset_lesson)) {
1062 $lessonssql = "SELECT l.id
646fc290 1063 FROM {lesson} l
1064 WHERE l.course=:course";
1065
1066 $params = array ("course" => $data->courseid);
ebf5ad4f
JMV
1067 $lessons = $DB->get_records_sql($lessonssql, $params);
1068
1069 // Get rid of attempts files.
1070 $fs = get_file_storage();
1071 if ($lessons) {
1072 foreach ($lessons as $lessonid => $unused) {
1073 if (!$cm = get_coursemodule_from_instance('lesson', $lessonid)) {
1074 continue;
1075 }
1076 $context = context_module::instance($cm->id);
1077 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses');
1078 }
1079 }
1080
646fc290 1081 $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params);
646fc290 1082 $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params);
1083 $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params);
91d90081 1084 $DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params);
0b5a80a1 1085
1086 // remove all grades from gradebook
1087 if (empty($data->reset_gradebook_grades)) {
1088 lesson_reset_gradebook($data->courseid);
1089 }
1090
1091 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false);
1092 }
1093
e0e1a83e
JMV
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));
1098 $status[] = array(
1099 'component' => $componentstr,
1100 'item' => get_string('useroverridesdeleted', 'lesson'),
1101 'error' => false);
1102 }
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));
1107 $status[] = array(
1108 'component' => $componentstr,
1109 'item' => get_string('groupoverridesdeleted', 'lesson'),
1110 'error' => false);
1111 }
0b5a80a1 1112 /// updating dates - shift may be negative too
1113 if ($data->timeshift) {
e0e1a83e
JMV
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));
1122
0d14fcbc
AA
1123 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
1124 // See MDL-9367.
0b5a80a1 1125 shift_course_mod_dates('lesson', array('available', 'deadline'), $data->timeshift, $data->courseid);
1126 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
1127 }
1128
1129 return $status;
1130}
1131
f432bebf 1132/**
1133 * Returns all other caps used in module
8cc86111 1134 * @return array
f432bebf 1135 */
1136function lesson_get_extra_capabilities() {
1137 return array('moodle/site:accessallgroups');
1138}
1139
18a2a0cb 1140/**
8cc86111 1141 * @uses FEATURE_GROUPS
1142 * @uses FEATURE_GROUPINGS
8cc86111 1143 * @uses FEATURE_MOD_INTRO
1144 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1145 * @uses FEATURE_GRADE_HAS_GRADE
1146 * @uses FEATURE_GRADE_OUTCOMES
18a2a0cb 1147 * @param string $feature FEATURE_xx constant for requested feature
8cc86111 1148 * @return mixed True if module supports feature, false if not, null if doesn't know
18a2a0cb 1149 */
1150function lesson_supports($feature) {
1151 switch($feature) {
d8389172 1152 case FEATURE_GROUPS:
fdc790fc 1153 return true;
d8389172 1154 case FEATURE_GROUPINGS:
fdc790fc 1155 return true;
d8389172
DNA
1156 case FEATURE_MOD_INTRO:
1157 return true;
1158 case FEATURE_COMPLETION_TRACKS_VIEWS:
1159 return true;
1160 case FEATURE_GRADE_HAS_GRADE:
1161 return true;
25345cb4
JMV
1162 case FEATURE_COMPLETION_HAS_RULES:
1163 return true;
d8389172
DNA
1164 case FEATURE_GRADE_OUTCOMES:
1165 return true;
1166 case FEATURE_BACKUP_MOODLE2:
1167 return true;
1168 case FEATURE_SHOW_DESCRIPTION:
1169 return true;
1170 default:
1171 return null;
18a2a0cb 1172 }
1173}
c6949936 1174
25345cb4
JMV
1175/**
1176 * Obtains the automatic completion state for this lesson based on any conditions
1177 * in lesson settings.
1178 *
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.
1184 */
1185function lesson_get_completion_state($course, $cm, $userid, $type) {
1186 global $CFG, $DB;
1187
1188 // Get lesson details.
1189 $lesson = $DB->get_record('lesson', array('id' => $cm->instance), '*',
1190 MUST_EXIST);
1191
d0445cf7 1192 $result = $type; // Default return value.
25345cb4
JMV
1193 // If completion option is enabled, evaluate it and return true/false.
1194 if ($lesson->completionendreached) {
d0445cf7 1195 $value = $DB->record_exists('lesson_timer', array(
25345cb4 1196 'lessonid' => $lesson->id, 'userid' => $userid, 'completed' => 1));
d0445cf7
JMV
1197 if ($type == COMPLETION_AND) {
1198 $result = $result && $value;
1199 } else {
1200 $result = $result || $value;
1201 }
1202 }
10e2355f 1203 if ($lesson->completiontimespent != 0) {
d0445cf7
JMV
1204 $duration = $DB->get_field_sql(
1205 "SELECT SUM(lessontime - starttime)
1206 FROM {lesson_timer}
1207 WHERE lessonid = :lessonid
1208 AND userid = :userid",
1209 array('userid' => $userid, 'lessonid' => $lesson->id));
1210 if (!$duration) {
1211 $duration = 0;
1212 }
1213 if ($type == COMPLETION_AND) {
10e2355f 1214 $result = $result && ($lesson->completiontimespent < $duration);
d0445cf7 1215 } else {
10e2355f 1216 $result = $result || ($lesson->completiontimespent < $duration);
d0445cf7 1217 }
25345cb4 1218 }
d0445cf7 1219 return $result;
25345cb4 1220}
c6949936 1221/**
1222 * This function extends the settings navigation block for the site.
1223 *
1224 * It is safe to rely on PAGE here as we will only ever be within the module
1225 * context when this is called
1226 *
0b29477b
SH
1227 * @param settings_navigation $settings
1228 * @param navigation_node $lessonnode
c6949936 1229 */
0b29477b
SH
1230function lesson_extend_settings_navigation($settings, $lessonnode) {
1231 global $PAGE, $DB;
0a4abb73 1232
e0e1a83e
JMV
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();
1236 $beforekey = null;
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];
1242 }
1243
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);
1250
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);
1255 }
1256
5fc6a9e7 1257 if (has_capability('mod/lesson:edit', $PAGE->cm->context)) {
43fd7949
JO
1258 $url = new moodle_url('/mod/lesson/view.php', array('id' => $PAGE->cm->id));
1259 $lessonnode->add(get_string('preview', 'lesson'), $url);
02ff22e9
JO
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);
c6949936 1265 }
1266
b69d512a 1267 if (has_capability('mod/lesson:viewreports', $PAGE->cm->context)) {
3406acde 1268 $reportsnode = $lessonnode->add(get_string('reports', 'lesson'));
a6855934 1269 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportoverview'));
3406acde 1270 $reportsnode->add(get_string('overview', 'lesson'), $url);
a6855934 1271 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportdetail'));
3406acde 1272 $reportsnode->add(get_string('detailedstats', 'lesson'), $url);
c6949936 1273 }
1274
5fc6a9e7 1275 if (has_capability('mod/lesson:grade', $PAGE->cm->context)) {
a6855934 1276 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm->id));
0b29477b 1277 $lessonnode->add(get_string('manualgrading', 'lesson'), $url);
c6949936 1278 }
1279
3406acde 1280}
0a4abb73
SH
1281
1282/**
1283 * Get list of available import or export formats
1284 *
1285 * Copied and modified from lib/questionlib.php
1286 *
1287 * @param string $type 'import' if import list, otherwise export list assumed
1288 * @return array sorted list of import/export formats available
1289 */
1290function lesson_get_import_export_formats($type) {
1291 global $CFG;
bd3b3bba 1292 $fileformats = core_component::get_plugin_list("qformat");
0a4abb73
SH
1293
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);
1299 } else {
1300 continue;
1301 }
1302 $classname = "qformat_$fileformat";
1303 $format_class = new $classname();
1304 if ($type=='import') {
1305 $provided = $format_class->provide_import();
1306 } else {
1307 $provided = $format_class->provide_export();
1308 }
1309 if ($provided) {
64679179 1310 $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat);
0a4abb73
SH
1311 }
1312 }
1313 natcasesort($fileformatnames);
1314
1315 return $fileformatnames;
1316}
1317
1318/**
1319 * Serves the lesson attachments. Implements needed access control ;-)
1320 *
d2b7803e
DC
1321 * @package mod_lesson
1322 * @category files
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
261cbbac 1329 * @param array $options additional options affecting the file serving
0a4abb73
SH
1330 * @return bool false if file not found, does not return if found - justsend the file
1331 */
261cbbac 1332function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
0a4abb73
SH
1333 global $CFG, $DB;
1334
64f93798 1335 if ($context->contextlevel != CONTEXT_MODULE) {
0a4abb73
SH
1336 return false;
1337 }
2f67a9b3 1338
0a4abb73
SH
1339 $fileareas = lesson_get_file_areas();
1340 if (!array_key_exists($filearea, $fileareas)) {
1341 return false;
1342 }
1343
64f93798 1344 if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance))) {
0a4abb73
SH
1345 return false;
1346 }
1347
1348 require_course_login($course, true, $cm);
1349
64f93798 1350 if ($filearea === 'page_contents') {
0a4abb73
SH
1351 $pageid = (int)array_shift($args);
1352 if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) {
1353 return false;
1354 }
64f93798 1355 $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args);
64f93798 1356
0abc18cf
JMV
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))) {
1360 return false;
1361 }
1362 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1363
ebf5ad4f
JMV
1364 } else if ($filearea === 'essay_responses') {
1365 $itemid = (int)array_shift($args);
1366 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $itemid))) {
1367 return false;
1368 }
1369 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1370
3d1b7452 1371 } else if ($filearea === 'mediafile') {
63fe00c9
FM
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.
1375 array_shift($args);
1376 }
3d1b7452
PS
1377 $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args);
1378
1379 } else {
1380 return false;
0a4abb73
SH
1381 }
1382
1383 $fs = get_file_storage();
1384 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1385 return false;
1386 }
1387
1388 // finally send the file
261cbbac 1389 send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security!
0a4abb73
SH
1390}
1391
1392/**
1393 * Returns an array of file areas
d2b7803e
DC
1394 *
1395 * @package mod_lesson
1396 * @category files
d2b7803e 1397 * @return array a list of available file areas
0a4abb73
SH
1398 */
1399function lesson_get_file_areas() {
64f93798 1400 $areas = array();
89133afa
FM
1401 $areas['page_contents'] = get_string('pagecontents', 'mod_lesson');
1402 $areas['mediafile'] = get_string('mediafile', 'mod_lesson');
0abc18cf
JMV
1403 $areas['page_answers'] = get_string('pageanswers', 'mod_lesson');
1404 $areas['page_responses'] = get_string('pageresponses', 'mod_lesson');
ebf5ad4f 1405 $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson');
3d1b7452 1406 return $areas;
0a4abb73
SH
1407}
1408
1409/**
1410 * Returns a file_info_stored object for the file being requested here
1411 *
d2b7803e
DC
1412 * @package mod_lesson
1413 * @category files
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
0a4abb73
SH
1424 * @return file_info_stored
1425 */
1426function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
b47dc5ff
FM
1427 global $CFG, $DB;
1428
1429 if (!has_capability('moodle/course:managefiles', $context)) {
1430 // No peaking here for students!
64f93798
PS
1431 return null;
1432 }
1433
b47dc5ff
FM
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)) {
1437 $itemid = 0;
1438 }
1439
1440 if (is_null($itemid)) {
b47dc5ff
FM
1441 return new mod_lesson_file_info($browser, $course, $cm, $context, $areas, $filearea);
1442 }
1443
0a4abb73
SH
1444 $fs = get_file_storage();
1445 $filepath = is_null($filepath) ? '/' : $filepath;
1446 $filename = is_null($filename) ? '.' : $filename;
64f93798 1447 if (!$storedfile = $fs->get_file($context->id, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) {
0a4abb73
SH
1448 return null;
1449 }
b47dc5ff
FM
1450
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));
1455 } else {
1456 $areas = lesson_get_file_areas();
1457 if (isset($areas[$filearea])) {
1458 $itemname = $areas[$filearea];
1459 }
1460 }
1461
1462 $urlbase = $CFG->wwwroot . '/pluginfile.php';
1463 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false);
0a4abb73 1464}
b1627a92
DC
1465
1466
1467/**
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
1472 */
b38e2e28 1473function lesson_page_type_list($pagetype, $parentcontext, $currentcontext) {
346a32a7
AD
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'));
b1627a92
DC
1478 return $module_pagetype;
1479}
684c3be7
MN
1480
1481/**
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.
1485 *
1486 * @param int $lessonid the lesson id
1487 * @param stdClass $context the context
1488 * @param int $draftitemid the draft item
1489 */
1490function lesson_update_media_file($lessonid, $context, $draftitemid) {
1491 global $DB;
1492
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));
1505 } else {
1506 // Set the mediafile column in the lessons table.
1507 $DB->set_field('lesson', 'mediafile', '', array('id' => $lessonid));
1508 }
1509}
2b931458
DW
1510
1511/**
1512 * Get icon mapping for font-awesome.
1513 */
1514function mod_lesson_get_fontawesome_icon_map() {
1515 return [
1516 'mod_lesson:e/copy' => 'fa-clone',
1517 ];
1518}
635721f5
JL
1519
1520/*
1521 * Check if the module has any update that affects the current user since a given time.
1522 *
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
1527 * @since Moodle 3.3
1528 */
1529function lesson_check_updates_since(cm_info $cm, $from, $filter = array()) {
1530 global $DB, $USER;
1531
1532 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1533
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 > ?)';
0a348387 1538 $params = array($cm->instance, $from, $from);
635721f5
JL
1539
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);
1544 }
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);
1549 }
1550
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);
1556
1557 $select = 'lessonid = ? AND userid = ? AND timeseen > ?';
1558 $params = array($cm->instance, $USER->id, $from);
1559
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);
1564 }
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);
1569 }
1570
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);
1576 }
1577
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);
1584 }
1585
0a348387
JL
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);
1590
1591 $insql = '';
1592 $inparams = [];
1593 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1594 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1595 if (empty($groupusers)) {
1596 return $updates;
1597 }
1598 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1599 $select .= ' AND userid ' . $insql;
1600 $params = array_merge($params, $inparams);
1601 }
1602
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);
1607
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);
1612 }
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);
1617 }
1618
56da66ad
JL
1619 $select = 'lessonid = ? AND completed > ?';
1620 if (!empty($insql)) {
1621 $select .= ' AND userid ' . $insql;
1622 }
0a348387
JL
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);
1627 }
1628
56da66ad 1629 $select = 'lessonid = ? AND (starttime > ? OR lessontime > ? OR timemodifiedoffline > ?)';
0a348387 1630 $params = array($cm->instance, $from, $from, $from);
56da66ad
JL
1631 if (!empty($insql)) {
1632 $select .= ' AND userid ' . $insql;
1633 $params = array_merge($params, $inparams);
1634 }
0a348387
JL
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);
1639 }
1640 }
635721f5
JL
1641 return $updates;
1642}
8a8bd425
CB
1643
1644/**
59391e80
MN
1645 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1646 *
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.
8a8bd425 1649 *
e1cd93ce 1650 * @param calendar_event $event
8a8bd425 1651 * @param \core_calendar\action_factory $factory
01f96180 1652 * @return \core_calendar\local\event\entities\action_interface|null
8a8bd425 1653 */
e1cd93ce 1654function mod_lesson_core_calendar_provide_event_action(calendar_event $event,
8a8bd425 1655 \core_calendar\action_factory $factory) {
aa1cdff5 1656 global $DB, $CFG, $USER;
8a8bd425
CB
1657 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
1658
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));
1661
bfc8fbea
RW
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.
1664 return null;
1665 }
1666
aa1cdff5
CB
1667 // Apply overrides.
1668 $lesson->update_effective_access($USER->id);
1669
8a8bd425
CB
1670 return $factory->create_instance(
1671 get_string('startlesson', 'lesson'),
1672 new \moodle_url('/mod/lesson/view.php', ['id' => $cm->id]),
1673 1,
1674 $lesson->is_accessible()
1675 );
1676}
b54bcddd
JD
1677
1678/**
1679 * Add a get_coursemodule_info function in case any lesson type wants to add 'extra' information
1680 * for the course (see resource).
1681 *
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.
1684 *
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).
1688 */
1689function lesson_get_coursemodule_info($coursemodule) {
1690 global $DB;
1691
1692 $dbparams = ['id' => $coursemodule->instance];
438c01d0 1693 $fields = 'id, name, intro, introformat, completionendreached, completiontimespent';
b54bcddd
JD
1694 if (!$lesson = $DB->get_record('lesson', $dbparams, $fields)) {
1695 return false;
1696 }
1697
1698 $result = new cached_cm_info();
23e5104a 1699 $result->name = $lesson->name;
b54bcddd 1700
438c01d0
MG
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);
1704 }
1705
b54bcddd
JD
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;
1710 }
1711
1712 return $result;
1713}
1714
1715/**
1716 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1717 *
7f53e8aa 1718 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
b54bcddd
JD
1719 * @return array $descriptions the array of descriptions for the custom rules.
1720 */
1721function mod_lesson_get_completion_active_rule_descriptions($cm) {
1722 // Values will be present in cm_info, and we assume these are up to date.
7f53e8aa 1723 if (empty($cm->customdata['customcompletionrules'])
b54bcddd
JD
1724 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1725 return [];
1726 }
1727
1728 $descriptions = [];
1729 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1730 switch ($key) {
1731 case 'completionendreached':
1732 if (empty($val)) {
1733 continue;
1734 }
1735 $descriptions[] = get_string('completionendreached_desc', 'lesson', $val);
1736 break;
1737 case 'completiontimespent':
1738 if (empty($val)) {
1739 continue;
1740 }
1741 $descriptions[] = get_string('completiontimespentdesc', 'lesson', format_time($val));
1742 break;
1743 default:
1744 break;
1745 }
1746 }
1747 return $descriptions;
1748}