MDL-60057 mod_lesson: add calendar drag and drop callbacks
[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
f077e0af
SL
28// Event types.
29define('LESSON_EVENT_TYPE_OPEN', 'open');
30define('LESSON_EVENT_TYPE_CLOSE', 'close');
31
1e7f8ea2 32/* Do not include any libraries here! */
97c44107 33
acf85537 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.
39 *
8cc86111 40 * @global object
41 * @global object
acf85537 42 * @param object $lesson Lesson post data from the form
43 * @return int
44 **/
0a4abb73 45function lesson_add_instance($data, $mform) {
1e7f8ea2 46 global $DB;
bbcbc0fe 47
0a4abb73 48 $cmid = $data->coursemodule;
684c3be7
MN
49 $draftitemid = $data->mediafile;
50 $context = context_module::instance($cmid);
5f649aaa 51
0a4abb73 52 lesson_process_pre_save($data);
271fea97 53
0a4abb73
SH
54 unset($data->mediafile);
55 $lessonid = $DB->insert_record("lesson", $data);
56 $data->id = $lessonid;
97c44107 57
684c3be7 58 lesson_update_media_file($lessonid, $context, $draftitemid);
0a4abb73
SH
59
60 lesson_process_post_save($data);
61
62 lesson_grade_item_update($data);
92bcca38 63
b5914b61 64 return $lessonid;
bbcbc0fe 65}
66
acf85537 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.
71 *
8cc86111 72 * @global object
acf85537 73 * @param object $lesson Lesson post data from the form
74 * @return boolean
75 **/
0a4abb73 76function lesson_update_instance($data, $mform) {
c18269c7 77 global $DB;
bbcbc0fe 78
0a4abb73
SH
79 $data->id = $data->instance;
80 $cmid = $data->coursemodule;
684c3be7
MN
81 $draftitemid = $data->mediafile;
82 $context = context_module::instance($cmid);
1535c81b 83
0a4abb73 84 lesson_process_pre_save($data);
97c44107 85
0a4abb73 86 unset($data->mediafile);
1e7f8ea2 87 $DB->update_record("lesson", $data);
97c44107 88
684c3be7 89 lesson_update_media_file($data->id, $context, $draftitemid);
0a4abb73
SH
90
91 lesson_process_post_save($data);
92bcca38 92
93 // update grade item definition
0a4abb73 94 lesson_grade_item_update($data);
92bcca38 95
96 // update grades - TODO: do it only when grading style changes
0a4abb73 97 lesson_update_grades($data, 0, false);
92bcca38 98
1e7f8ea2 99 return true;
bbcbc0fe 100}
101
e0e1a83e
JMV
102/**
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.
106 *
107 * @uses LESSON_MAX_EVENT_LENGTH
108 * @param object $lesson the lesson object.
109 * @param object $override (optional) limit to a specific override
110 */
111function lesson_update_events($lesson, $override = null) {
112 global $CFG, $DB;
113
9ff8cdd9 114 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
e0e1a83e
JMV
115 require_once($CFG->dirroot . '/calendar/lib.php');
116
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;
126 }
127 }
8dada7e3 128 $oldevents = $DB->get_records('event', $conds, 'id ASC');
e0e1a83e 129
98239b2d 130 // Now make a to-do list of all that needs to be updated.
e0e1a83e 131 if (empty($override)) {
98239b2d 132 // We are updating the primary settings for the lesson, so we need to add all the overrides.
8dada7e3
CB
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());
e0e1a83e
JMV
139 } else {
140 // Just do the one override.
141 $overrides = array($override);
142 }
143
98239b2d
JP
144 // Get group override priorities.
145 $grouppriorities = lesson_get_group_override_priorities($lesson->id);
146
e0e1a83e
JMV
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;
152
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);
156
157 if (!empty($lesson->coursemodule)) {
158 $cmid = $lesson->coursemodule;
159 } else {
160 $cmid = get_coursemodule_from_instance('lesson', $lesson->id, $lesson->course)->id;
161 }
162
163 $event = new stdClass();
8a8bd425 164 $event->type = !$deadline ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
e0e1a83e
JMV
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);
8a8bd425 174 $event->timesort = $available;
e0e1a83e 175 $event->visible = instance_is_visible('lesson', $lesson);
8a8bd425 176 $event->eventtype = LESSON_EVENT_TYPE_OPEN;
8dada7e3 177 $event->priority = null;
e0e1a83e 178
98239b2d 179 // Determine the event name and priority.
e0e1a83e 180 if ($groupid) {
98239b2d 181 // Group override event.
e0e1a83e
JMV
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;
188 }
189 $eventname = get_string('overridegroupeventname', 'lesson', $params);
98239b2d
JP
190 // Set group override priority.
191 if ($grouppriorities !== null) {
192 $openpriorities = $grouppriorities['open'];
193 if (isset($openpriorities[$available])) {
194 $event->priority = $openpriorities[$available];
195 }
196 }
e0e1a83e 197 } else if ($userid) {
98239b2d 198 // User override event.
e0e1a83e
JMV
199 $params = new stdClass();
200 $params->lesson = $lesson->name;
201 $eventname = get_string('overrideusereventname', 'lesson', $params);
98239b2d
JP
202 // Set user override priority.
203 $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
e0e1a83e 204 } else {
98239b2d 205 // The parent event.
e0e1a83e
JMV
206 $eventname = $lesson->name;
207 }
98239b2d 208
e0e1a83e 209 if ($addopen or $addclose) {
98239b2d
JP
210 // Separate start and end events.
211 $event->timeduration = 0;
212 if ($available && $addopen) {
e0e1a83e
JMV
213 if ($oldevent = array_shift($oldevents)) {
214 $event->id = $oldevent->id;
215 } else {
216 unset($event->id);
217 }
f10721d6 218 $event->name = get_string('lessoneventopens', 'lesson', $eventname);
e0e1a83e
JMV
219 // The method calendar_event::create will reuse a db record if the id field is set.
220 calendar_event::create($event);
98239b2d
JP
221 }
222 if ($deadline && $addclose) {
223 if ($oldevent = array_shift($oldevents)) {
224 $event->id = $oldevent->id;
225 } else {
226 unset($event->id);
e0e1a83e 227 }
8a8bd425 228 $event->type = CALENDAR_EVENT_TYPE_ACTION;
fac50516 229 $event->name = get_string('lessoneventcloses', 'lesson', $eventname);
98239b2d 230 $event->timestart = $deadline;
8a8bd425
CB
231 $event->timesort = $deadline;
232 $event->eventtype = LESSON_EVENT_TYPE_CLOSE;
98239b2d
JP
233 if ($groupid && $grouppriorities !== null) {
234 $closepriorities = $grouppriorities['close'];
235 if (isset($closepriorities[$deadline])) {
236 $event->priority = $closepriorities[$deadline];
e0e1a83e 237 }
e0e1a83e 238 }
98239b2d 239 calendar_event::create($event);
e0e1a83e
JMV
240 }
241 }
242 }
243
244 // Delete any leftover events.
245 foreach ($oldevents as $badevent) {
246 $badevent = calendar_event::load($badevent);
247 $badevent->delete();
248 }
249}
250
efe24976
JP
251/**
252 * Calculates the priorities of timeopen and timeclose values for group overrides for a lesson.
253 *
756a132f 254 * @param int $lessonid The lesson ID.
efe24976
JP
255 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
256 */
257function lesson_get_group_override_priorities($lessonid) {
258 global $DB;
259
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;
266 }
267
268 $grouptimeopen = [];
269 $grouptimeclose = [];
270 foreach ($overrides as $override) {
271 if ($override->available !== null && !in_array($override->available, $grouptimeopen)) {
272 $grouptimeopen[] = $override->available;
273 }
274 if ($override->deadline !== null && !in_array($override->deadline, $grouptimeclose)) {
275 $grouptimeclose[] = $override->deadline;
276 }
277 }
278
756a132f
CB
279 // Sort open times in ascending manner. The earlier open time gets higher priority.
280 sort($grouptimeopen);
efe24976
JP
281 // Set priorities.
282 $opengrouppriorities = [];
283 $openpriority = 1;
284 foreach ($grouptimeopen as $timeopen) {
285 $opengrouppriorities[$timeopen] = $openpriority++;
286 }
287
756a132f
CB
288 // Sort close times in descending manner. The later close time gets higher priority.
289 rsort($grouptimeclose);
efe24976
JP
290 // Set priorities.
291 $closegrouppriorities = [];
292 $closepriority = 1;
293 foreach ($grouptimeclose as $timeclose) {
294 $closegrouppriorities[$timeclose] = $closepriority++;
295 }
296
297 return [
298 'open' => $opengrouppriorities,
299 'close' => $closegrouppriorities
300 ];
301}
302
e0e1a83e
JMV
303/**
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()
309 *
310 * @param int $courseid
9ffbdafc
AG
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).
e0e1a83e
JMV
313 * @return bool
314 */
9ffbdafc 315function lesson_refresh_events($courseid = 0, $instance = null, $cm = null) {
e0e1a83e
JMV
316 global $DB;
317
9ffbdafc
AG
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);
322 }
323 lesson_update_events($instance);
324 return true;
325 }
326
e0e1a83e 327 if ($courseid == 0) {
2b9d9740 328 if (!$lessons = $DB->get_records('lesson')) {
e0e1a83e
JMV
329 return true;
330 }
331 } else {
332 if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) {
333 return true;
334 }
335 }
336
337 foreach ($lessons as $lesson) {
338 lesson_update_events($lesson);
339 }
340
341 return true;
342}
bbcbc0fe 343
8cc86111 344/**
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.
348 *
349 * @global object
350 * @param int $id
351 * @return bool
352 */
bbcbc0fe 353function lesson_delete_instance($id) {
3d53d99e
PS
354 global $DB, $CFG;
355 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
356
0a4abb73
SH
357 $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST);
358 $lesson = new lesson($lesson);
359 return $lesson->delete();
bbcbc0fe 360}
361
8cc86111 362/**
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
368 *
369 * @global object
370 * @param object $course
371 * @param object $user
372 * @param object $mod
373 * @param object $lesson
374 * @return object
375 */
bbcbc0fe 376function lesson_user_outline($course, $user, $mod, $lesson) {
fbf85b8d 377 global $CFG, $DB;
df0442c6 378
1a96363a
NC
379 require_once("$CFG->libdir/gradelib.php");
380 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
39790bd8 381 $return = new stdClass();
fbf85b8d 382
1a96363a 383 if (empty($grades->items[0]->grades)) {
fbf85b8d 384 $return->info = get_string("nolessonattempts", "lesson");
bbcbc0fe 385 } else {
1a96363a 386 $grade = reset($grades->items[0]->grades);
fbf85b8d
SB
387 if (empty($grade->grade)) {
388
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);
396
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");
403 }
404 $return->time = $attempt->lessontime;
405 } else {
406 $return->info = get_string("nolessonattempts", "lesson");
407 }
4433f871 408 } else {
fbf85b8d
SB
409 $return->info = get_string("grade") . ': ' . $grade->str_long_grade;
410
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;
418 }
4433f871 419 }
bbcbc0fe 420 }
421 return $return;
422}
423
8cc86111 424/**
425 * Print a detailed representation of what a user has done with
426 * a given particular instance of this module, for user activity reports.
427 *
428 * @global object
429 * @param object $course
430 * @param object $user
431 * @param object $mod
432 * @param object $lesson
433 * @return bool
434 */
bbcbc0fe 435function lesson_user_complete($course, $user, $mod, $lesson) {
1a96363a
NC
436 global $DB, $OUTPUT, $CFG;
437
438 require_once("$CFG->libdir/gradelib.php");
439
440 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
764c4fbc
SB
441
442 // Display the grade and feedback.
443 if (empty($grades->items[0]->grades)) {
444 echo $OUTPUT->container(get_string("nolessonattempts", "lesson"));
445 } else {
1a96363a 446 $grade = reset($grades->items[0]->grades);
764c4fbc
SB
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);
455
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");
461 }
462 } else {
463 $status = get_string("nolessonattempts", "lesson");
464 }
465 } else {
466 $status = get_string("grade") . ': ' . $grade->str_long_grade;
467 }
468
469 // Display the grade or lesson status if there isn't one.
470 echo $OUTPUT->container($status);
471
1a96363a
NC
472 if ($grade->str_feedback) {
473 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
474 }
475 }
fe75e76b 476
764c4fbc
SB
477 // Display the lesson progress.
478 // Attempt, pages viewed, questions answered, correct answers, time.
646fc290 479 $params = array ("lessonid" => $lesson->id, "userid" => $user->id);
764c4fbc
SB
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)) {
d68ccdba 483 echo $OUTPUT->box_start();
3ab269ed 484 $table = new html_table();
764c4fbc
SB
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"));
ac8e16be 491 $table->width = "100%";
764c4fbc
SB
492 $table->align = array ("center", "center", "center", "center", "center");
493 $table->size = array ("*", "*", "*", "*", "*");
ac8e16be 494 $table->cellpadding = 2;
495 $table->cellspacing = 0;
bbcbc0fe 496
497 $retry = 0;
764c4fbc 498 $nquestions = 0;
bbcbc0fe 499 $npages = 0;
500 $ncorrect = 0;
5f649aaa 501
764c4fbc 502 // Filter question pages (from lesson_attempts).
ac8e16be 503 foreach ($attempts as $attempt) {
504 if ($attempt->retry == $retry) {
505 $npages++;
764c4fbc 506 $nquestions++;
bbcbc0fe 507 if ($attempt->correct) {
508 $ncorrect++;
509 }
510 $timeseen = $attempt->timeseen;
511 } else {
764c4fbc 512 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
bbcbc0fe 513 $retry++;
764c4fbc 514 $nquestions = 1;
bbcbc0fe 515 $npages = 1;
516 if ($attempt->correct) {
517 $ncorrect = 1;
518 } else {
519 $ncorrect = 0;
520 }
ac8e16be 521 }
522 }
764c4fbc
SB
523
524 // Filter content pages (from lesson_branch).
525 foreach ($branches as $branch) {
526 if ($branch->retry == $retry) {
527 $npages++;
528
529 $timeseen = $branch->timeseen;
530 } else {
531 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
532 $retry++;
533 $npages = 1;
534 }
535 }
536 if ($npages > 0) {
537 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
bbcbc0fe 538 }
16be8974 539 echo html_writer::table($table);
d68ccdba 540 echo $OUTPUT->box_end();
bbcbc0fe 541 }
542
bbcbc0fe 543 return true;
544}
545
4342dc32 546/**
547 * Prints lesson summaries on MyMoodle Page
548 *
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.
552 *
e9dfeec9 553 * @deprecated since 3.3
063b7ee6 554 * @todo The final deprecation of this function will take place in Moodle 3.7 - see MDL-57487.
8cc86111 555 * @global object
556 * @global stdClass
557 * @global object
558 * @uses CONTEXT_MODULE
4342dc32 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 )
8cc86111 561 * @return void
4342dc32 562 */
563function lesson_print_overview($courses, &$htmlarray) {
fe75e76b 564 global $USER, $CFG, $DB, $OUTPUT;
4342dc32 565
e9dfeec9
MN
566 debugging('The function lesson_print_overview() is now deprecated.', DEBUG_DEVELOPER);
567
4342dc32 568 if (!$lessons = get_all_instances_in_courses('lesson', $courses)) {
569 return;
570 }
571
673e0d5a
SB
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;
582 }
583
584 // Get the current course ID.
585 $listoflessons = array();
586 foreach ($lessons as $lesson) {
587 $listoflessons[] = $lesson->id;
588 }
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);
2c4b43d9
MN
591 $dbparams = array_merge($inparams, array('userid' => $USER->id));
592
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);
615
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);
673e0d5a
SB
620
621 $lastviewed = array();
622 foreach ($lastattempts as $lastattempt) {
2c4b43d9
MN
623 $lastviewed[$lastattempt->lessonid] = $lastattempt;
624 }
625
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;
673e0d5a
SB
633 }
634 }
635
636 // Since we have lessons in this course, now include the constants we need.
637 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
4342dc32 638
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
644
673e0d5a
SB
645 // Visibility.
646 $class = (!$lesson->visible) ? 'dimmed' : '';
4342dc32 647
673e0d5a
SB
648 // Context.
649 $context = context_module::instance($lesson->coursemodule);
4342dc32 650
673e0d5a
SB
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');
655
656 // Deadline.
fe75e76b 657 $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info');
4342dc32 658
673e0d5a
SB
659 // Attempt information.
660 if (has_capability('mod/lesson:manage', $context)) {
661 // This is a teacher, Get the Number of user attempts.
c1500a82 662 $attempts = $DB->count_records('lesson_grades', array('lessonid' => $lesson->id));
fe75e76b 663 $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info');
673e0d5a 664 $str = $OUTPUT->box($str, 'lesson overview');
4342dc32 665 } else {
673e0d5a
SB
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 = '';
679 }
680
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 = '';
696 }
697
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');
702 }
703
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');
708 }
709 }
710
4342dc32 711 } else {
673e0d5a
SB
712 // User has not yet started this lesson.
713 $str .= $OUTPUT->box(get_string('nolessonattempts', 'lesson'), 'info');
714 $str = $OUTPUT->box($str, 'lesson overview');
4342dc32 715 }
716 }
673e0d5a
SB
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;
722 }
4342dc32 723 }
724 }
725 }
726}
727
8cc86111 728/**
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
734 */
bbcbc0fe 735function lesson_cron () {
bbcbc0fe 736 global $CFG;
737
738 return true;
739}
740
92bcca38 741/**
742 * Return grade for given user or all users.
743 *
8cc86111 744 * @global stdClass
745 * @global object
92bcca38 746 * @param int $lessonid id of lesson
747 * @param int $userid optional user id, 0 means all users
8a8bd425 748 * @return array array of grades, false if none
92bcca38 749 */
750function lesson_get_user_grades($lesson, $userid=0) {
646fc290 751 global $CFG, $DB;
bbcbc0fe 752
b920f6e8 753 $params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id);
fe75e76b 754
85c13c69 755 if (!empty($userid)) {
646fc290 756 $params["userid"] = $userid;
b920f6e8 757 $params["userid2"] = $userid;
646fc290 758 $user = "AND u.id = :userid";
b920f6e8 759 $fuser = "AND uu.id = :userid2";
646fc290 760 }
761 else {
e57bc529 762 $user="";
646fc290 763 $fuser="";
764 }
fe75e76b 765
512ce792 766 if ($lesson->retake) {
767 if ($lesson->usemaxgrade) {
ac9b0805 768 $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade
646fc290 769 FROM {user} u, {lesson_grades} g
770 WHERE u.id = g.userid AND g.lessonid = :lessonid
92bcca38 771 $user
772 GROUP BY u.id";
512ce792 773 } else {
ac9b0805 774 $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade
646fc290 775 FROM {user} u, {lesson_grades} g
776 WHERE u.id = g.userid AND g.lessonid = :lessonid
92bcca38 777 $user
778 GROUP BY u.id";
512ce792 779 }
96fa52a4 780 unset($params['lessonid2']);
781 unset($params['userid2']);
512ce792 782 } else {
92bcca38 783 // use only first attempts (with lowest id in lesson_grades table)
784 $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted
646fc290 785 FROM {user} uu, {lesson_grades} gg
b920f6e8 786 WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2
92bcca38 787 $fuser
788 GROUP BY uu.id";
789
ac9b0805 790 $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade
646fc290 791 FROM {user} u, {lesson_grades} g, ($firstonly) f
792 WHERE u.id = g.userid AND g.lessonid = :lessonid
92bcca38 793 AND g.id = f.firstcompleted AND g.userid=f.userid
794 $user";
795 }
796
646fc290 797 return $DB->get_records_sql($sql, $params);
92bcca38 798}
799
800/**
801 * Update grades in central gradebook
802 *
a153c9f2 803 * @category grade
775f811a 804 * @param object $lesson
805 * @param int $userid specific user only, 0 means all
8cc86111 806 * @param bool $nullifnone
92bcca38 807 */
775f811a 808function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
646fc290 809 global $CFG, $DB;
775f811a 810 require_once($CFG->libdir.'/gradelib.php');
92bcca38 811
c7d1a37b 812 if ($lesson->grade == 0 || $lesson->practice) {
775f811a 813 lesson_grade_item_update($lesson);
92bcca38 814
775f811a 815 } else if ($grades = lesson_get_user_grades($lesson, $userid)) {
816 lesson_grade_item_update($lesson, $grades);
eafb9d9e 817
775f811a 818 } else if ($userid and $nullifnone) {
39790bd8 819 $grade = new stdClass();
775f811a 820 $grade->userid = $userid;
ecea65ca 821 $grade->rawgrade = null;
775f811a 822 lesson_grade_item_update($lesson, $grade);
92bcca38 823
824 } else {
775f811a 825 lesson_grade_item_update($lesson);
826 }
827}
828
92bcca38 829/**
830 * Create grade item for given lesson
831 *
a153c9f2 832 * @category grade
8cc86111 833 * @uses GRADE_TYPE_VALUE
834 * @uses GRADE_TYPE_NONE
92bcca38 835 * @param object $lesson object with extra cmidnumber
8cc86111 836 * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
92bcca38 837 * @return int 0 if ok, error code otherwise
838 */
ecea65ca 839function lesson_grade_item_update($lesson, $grades=null) {
92bcca38 840 global $CFG;
841 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
842 require_once($CFG->libdir.'/gradelib.php');
843 }
844
845 if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present
846 $params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber);
ac8e16be 847 } else {
92bcca38 848 $params = array('itemname'=>$lesson->name);
ac8e16be 849 }
92bcca38 850
33ce9e58 851 if (!$lesson->practice and $lesson->grade > 0) {
92bcca38 852 $params['gradetype'] = GRADE_TYPE_VALUE;
91ca18e8 853 $params['grademax'] = $lesson->grade;
92bcca38 854 $params['grademin'] = 0;
33ce9e58 855 } else if (!$lesson->practice and $lesson->grade < 0) {
f51cda3d
AD
856 $params['gradetype'] = GRADE_TYPE_SCALE;
857 $params['scaleid'] = -$lesson->grade;
da7e5daf 858
16c25753
TL
859 // Make sure current grade fetched correctly from $grades
860 $currentgrade = null;
74dd3bd6 861 if (!empty($grades)) {
16c25753
TL
862 if (is_array($grades)) {
863 $currentgrade = reset($grades);
864 } else {
865 $currentgrade = $grades;
866 }
867 }
868
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);
74dd3bd6
TL
872 $params['grademax'] = reset($grade->items)->grademax;
873 }
92bcca38 874 } else {
875 $params['gradetype'] = GRADE_TYPE_NONE;
92bcca38 876 }
877
0b5a80a1 878 if ($grades === 'reset') {
879 $params['reset'] = true;
ecea65ca 880 $grades = null;
13b92708 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);
887 }
888 foreach ($grades as $key => $grade) {
889 if (!is_array($grade)) {
890 $grades[$key] = $grade = (array) $grade;
891 }
76027a9f
AD
892 //check raw grade isnt null otherwise we erroneously insert a grade of 0
893 if ($grade['rawgrade'] !== null) {
da7e5daf 894 $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100);
76027a9f
AD
895 } else {
896 //setting rawgrade to null just in case user is deleting a grade
897 $grades[$key]['rawgrade'] = null;
898 }
13b92708 899 }
0b5a80a1 900 }
901
902 return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params);
92bcca38 903}
904
8cc86111 905/**
b2b4ec30
RT
906 * List the actions that correspond to a view of this module.
907 * This is used by the participation report.
908 *
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.
912 *
8cc86111 913 * @return array
914 */
f3221af9 915function lesson_get_view_actions() {
cf051cc4 916 return array('view','view all');
f3221af9 917}
918
8cc86111 919/**
b2b4ec30
RT
920 * List the actions that correspond to a post of this module.
921 * This is used by the participation report.
922 *
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.
926 *
8cc86111 927 * @return array
928 */
f3221af9 929function lesson_get_post_actions() {
0a4abb73 930 return array('end','start');
f3221af9 931}
932
acf85537 933/**
934 * Runs any processes that must run before
935 * a lesson insert/update
936 *
8cc86111 937 * @global object
acf85537 938 * @param object $lesson Lesson form data
939 * @return void
940 **/
941function lesson_process_pre_save(&$lesson) {
646fc290 942 global $DB;
fe75e76b 943
acf85537 944 $lesson->timemodified = time();
945
a1acc001
JMV
946 if (empty($lesson->timelimit)) {
947 $lesson->timelimit = 0;
862bd9cd 948 }
acf85537 949 if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) {
950 $lesson->timespent = 0;
951 }
952 if (!isset($lesson->completed)) {
953 $lesson->completed = 0;
954 }
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;
959 }
960
0a4abb73
SH
961 if (empty($lesson->width)) {
962 $lesson->width = 640;
963 }
964 if (empty($lesson->height)) {
965 $lesson->height = 480;
966 }
967 if (empty($lesson->bgcolor)) {
968 $lesson->bgcolor = '#FFFFFF';
969 }
970
acf85537 971 // Conditions for dependency
972 $conditions = new stdClass;
973 $conditions->timespent = $lesson->timespent;
974 $conditions->completed = $lesson->completed;
975 $conditions->gradebetterthan = $lesson->gradebetterthan;
646fc290 976 $lesson->conditions = serialize($conditions);
acf85537 977 unset($lesson->timespent);
978 unset($lesson->completed);
979 unset($lesson->gradebetterthan);
980
4d22ec81 981 if (empty($lesson->password)) {
acf85537 982 unset($lesson->password);
983 }
acf85537 984}
985
986/**
987 * Runs any processes that must be run
988 * after a lesson insert/update
989 *
8cc86111 990 * @global object
acf85537 991 * @param object $lesson Lesson form data
992 * @return void
993 **/
994function lesson_process_post_save(&$lesson) {
e0e1a83e
JMV
995 // Update the events relating to this lesson.
996 lesson_update_events($lesson);
9ffbdafc
AG
997 $completionexpected = (!empty($lesson->completionexpected)) ? $lesson->completionexpected : null;
998 \core_completion\api::update_completion_date_event($lesson->coursemodule, 'lesson', $lesson, $completionexpected);
acf85537 999}
1000
0b5a80a1 1001
1002/**
1003 * Implementation of the function for printing the form elements that control
1004 * whether the course reset functionality affects the lesson.
fe75e76b 1005 *
0b5a80a1 1006 * @param $mform form passed by reference
1007 */
1008function 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'));
e0e1a83e
JMV
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'));
0b5a80a1 1015}
1016
1017/**
1018 * Course reset form defaults.
8cc86111 1019 * @param object $course
1020 * @return array
0b5a80a1 1021 */
1022function lesson_reset_course_form_defaults($course) {
e0e1a83e
JMV
1023 return array('reset_lesson' => 1,
1024 'reset_lesson_group_overrides' => 1,
1025 'reset_lesson_user_overrides' => 1);
0b5a80a1 1026}
1027
1028/**
1029 * Removes all grades from gradebook
8cc86111 1030 *
1031 * @global stdClass
1032 * @global object
0b5a80a1 1033 * @param int $courseid
1034 * @param string optional type
1035 */
1036function lesson_reset_gradebook($courseid, $type='') {
646fc290 1037 global $CFG, $DB;
0b5a80a1 1038
1039 $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
646fc290 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)) {
0b5a80a1 1044 foreach ($lessons as $lesson) {
1045 lesson_grade_item_update($lesson, 'reset');
1046 }
1047 }
1048}
1049
1050/**
72d2982e 1051 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 1052 * lesson attempts for course $data->courseid.
8cc86111 1053 *
1054 * @global stdClass
1055 * @global object
1056 * @param object $data the data submitted from the reset course.
0b5a80a1 1057 * @return array status array
1058 */
1059function lesson_reset_userdata($data) {
646fc290 1060 global $CFG, $DB;
0b5a80a1 1061
1062 $componentstr = get_string('modulenameplural', 'lesson');
1063 $status = array();
1064
1065 if (!empty($data->reset_lesson)) {
1066 $lessonssql = "SELECT l.id
646fc290 1067 FROM {lesson} l
1068 WHERE l.course=:course";
1069
1070 $params = array ("course" => $data->courseid);
ebf5ad4f
JMV
1071 $lessons = $DB->get_records_sql($lessonssql, $params);
1072
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;
1079 }
1080 $context = context_module::instance($cm->id);
1081 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses');
1082 }
1083 }
1084
646fc290 1085 $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params);
646fc290 1086 $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params);
1087 $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params);
91d90081 1088 $DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params);
0b5a80a1 1089
1090 // remove all grades from gradebook
1091 if (empty($data->reset_gradebook_grades)) {
1092 lesson_reset_gradebook($data->courseid);
1093 }
1094
1095 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false);
1096 }
1097
e0e1a83e
JMV
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);
1106 }
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);
1115 }
0b5a80a1 1116 /// updating dates - shift may be negative too
1117 if ($data->timeshift) {
e0e1a83e
JMV
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));
1126
0d14fcbc
AA
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.
0b5a80a1 1129 shift_course_mod_dates('lesson', array('available', 'deadline'), $data->timeshift, $data->courseid);
1130 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
1131 }
1132
1133 return $status;
1134}
1135
f432bebf 1136/**
1137 * Returns all other caps used in module
8cc86111 1138 * @return array
f432bebf 1139 */
1140function lesson_get_extra_capabilities() {
1141 return array('moodle/site:accessallgroups');
1142}
1143
18a2a0cb 1144/**
8cc86111 1145 * @uses FEATURE_GROUPS
1146 * @uses FEATURE_GROUPINGS
8cc86111 1147 * @uses FEATURE_MOD_INTRO
1148 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1149 * @uses FEATURE_GRADE_HAS_GRADE
1150 * @uses FEATURE_GRADE_OUTCOMES
18a2a0cb 1151 * @param string $feature FEATURE_xx constant for requested feature
8cc86111 1152 * @return mixed True if module supports feature, false if not, null if doesn't know
18a2a0cb 1153 */
1154function lesson_supports($feature) {
1155 switch($feature) {
d8389172 1156 case FEATURE_GROUPS:
fdc790fc 1157 return true;
d8389172 1158 case FEATURE_GROUPINGS:
fdc790fc 1159 return true;
d8389172
DNA
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;
25345cb4
JMV
1166 case FEATURE_COMPLETION_HAS_RULES:
1167 return true;
d8389172
DNA
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;
18a2a0cb 1176 }
1177}
c6949936 1178
25345cb4
JMV
1179/**
1180 * Obtains the automatic completion state for this lesson based on any conditions
1181 * in lesson settings.
1182 *
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.
1188 */
1189function lesson_get_completion_state($course, $cm, $userid, $type) {
1190 global $CFG, $DB;
1191
1192 // Get lesson details.
1193 $lesson = $DB->get_record('lesson', array('id' => $cm->instance), '*',
1194 MUST_EXIST);
1195
d0445cf7 1196 $result = $type; // Default return value.
25345cb4
JMV
1197 // If completion option is enabled, evaluate it and return true/false.
1198 if ($lesson->completionendreached) {
d0445cf7 1199 $value = $DB->record_exists('lesson_timer', array(
25345cb4 1200 'lessonid' => $lesson->id, 'userid' => $userid, 'completed' => 1));
d0445cf7
JMV
1201 if ($type == COMPLETION_AND) {
1202 $result = $result && $value;
1203 } else {
1204 $result = $result || $value;
1205 }
1206 }
10e2355f 1207 if ($lesson->completiontimespent != 0) {
d0445cf7
JMV
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;
1216 }
1217 if ($type == COMPLETION_AND) {
10e2355f 1218 $result = $result && ($lesson->completiontimespent < $duration);
d0445cf7 1219 } else {
10e2355f 1220 $result = $result || ($lesson->completiontimespent < $duration);
d0445cf7 1221 }
25345cb4 1222 }
d0445cf7 1223 return $result;
25345cb4 1224}
c6949936 1225/**
1226 * This function extends the settings navigation block for the site.
1227 *
1228 * It is safe to rely on PAGE here as we will only ever be within the module
1229 * context when this is called
1230 *
0b29477b
SH
1231 * @param settings_navigation $settings
1232 * @param navigation_node $lessonnode
c6949936 1233 */
0b29477b
SH
1234function lesson_extend_settings_navigation($settings, $lessonnode) {
1235 global $PAGE, $DB;
0a4abb73 1236
e0e1a83e
JMV
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];
1246 }
1247
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);
1254
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);
1259 }
1260
5fc6a9e7 1261 if (has_capability('mod/lesson:edit', $PAGE->cm->context)) {
43fd7949
JO
1262 $url = new moodle_url('/mod/lesson/view.php', array('id' => $PAGE->cm->id));
1263 $lessonnode->add(get_string('preview', 'lesson'), $url);
02ff22e9
JO
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);
c6949936 1269 }
1270
b69d512a 1271 if (has_capability('mod/lesson:viewreports', $PAGE->cm->context)) {
3406acde 1272 $reportsnode = $lessonnode->add(get_string('reports', 'lesson'));
a6855934 1273 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportoverview'));
3406acde 1274 $reportsnode->add(get_string('overview', 'lesson'), $url);
a6855934 1275 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportdetail'));
3406acde 1276 $reportsnode->add(get_string('detailedstats', 'lesson'), $url);
c6949936 1277 }
1278
5fc6a9e7 1279 if (has_capability('mod/lesson:grade', $PAGE->cm->context)) {
a6855934 1280 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm->id));
0b29477b 1281 $lessonnode->add(get_string('manualgrading', 'lesson'), $url);
c6949936 1282 }
1283
3406acde 1284}
0a4abb73
SH
1285
1286/**
1287 * Get list of available import or export formats
1288 *
1289 * Copied and modified from lib/questionlib.php
1290 *
1291 * @param string $type 'import' if import list, otherwise export list assumed
1292 * @return array sorted list of import/export formats available
1293 */
1294function lesson_get_import_export_formats($type) {
1295 global $CFG;
bd3b3bba 1296 $fileformats = core_component::get_plugin_list("qformat");
0a4abb73
SH
1297
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;
1305 }
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();
1312 }
1313 if ($provided) {
64679179 1314 $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat);
0a4abb73
SH
1315 }
1316 }
1317 natcasesort($fileformatnames);
1318
1319 return $fileformatnames;
1320}
1321
1322/**
1323 * Serves the lesson attachments. Implements needed access control ;-)
1324 *
d2b7803e
DC
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
261cbbac 1333 * @param array $options additional options affecting the file serving
0a4abb73
SH
1334 * @return bool false if file not found, does not return if found - justsend the file
1335 */
261cbbac 1336function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
0a4abb73
SH
1337 global $CFG, $DB;
1338
64f93798 1339 if ($context->contextlevel != CONTEXT_MODULE) {
0a4abb73
SH
1340 return false;
1341 }
2f67a9b3 1342
0a4abb73
SH
1343 $fileareas = lesson_get_file_areas();
1344 if (!array_key_exists($filearea, $fileareas)) {
1345 return false;
1346 }
1347
64f93798 1348 if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance))) {
0a4abb73
SH
1349 return false;
1350 }
1351
1352 require_course_login($course, true, $cm);
1353
64f93798 1354 if ($filearea === 'page_contents') {
0a4abb73
SH
1355 $pageid = (int)array_shift($args);
1356 if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) {
1357 return false;
1358 }
64f93798 1359 $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args);
64f93798 1360
0abc18cf
JMV
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;
1365 }
1366 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1367
ebf5ad4f
JMV
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;
1372 }
1373 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1374
3d1b7452 1375 } else if ($filearea === 'mediafile') {
63fe00c9
FM
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);
1380 }
3d1b7452
PS
1381 $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args);
1382
1383 } else {
1384 return false;
0a4abb73
SH
1385 }
1386
1387 $fs = get_file_storage();
1388 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1389 return false;
1390 }
1391
1392 // finally send the file
261cbbac 1393 send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security!
0a4abb73
SH
1394}
1395
1396/**
1397 * Returns an array of file areas
d2b7803e
DC
1398 *
1399 * @package mod_lesson
1400 * @category files
d2b7803e 1401 * @return array a list of available file areas
0a4abb73
SH
1402 */
1403function lesson_get_file_areas() {
64f93798 1404 $areas = array();
89133afa
FM
1405 $areas['page_contents'] = get_string('pagecontents', 'mod_lesson');
1406 $areas['mediafile'] = get_string('mediafile', 'mod_lesson');
0abc18cf
JMV
1407 $areas['page_answers'] = get_string('pageanswers', 'mod_lesson');
1408 $areas['page_responses'] = get_string('pageresponses', 'mod_lesson');
ebf5ad4f 1409 $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson');
3d1b7452 1410 return $areas;
0a4abb73
SH
1411}
1412
1413/**
1414 * Returns a file_info_stored object for the file being requested here
1415 *
d2b7803e
DC
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
0a4abb73
SH
1428 * @return file_info_stored
1429 */
1430function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
b47dc5ff
FM
1431 global $CFG, $DB;
1432
1433 if (!has_capability('moodle/course:managefiles', $context)) {
1434 // No peaking here for students!
64f93798
PS
1435 return null;
1436 }
1437
b47dc5ff
FM
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;
1442 }
1443
1444 if (is_null($itemid)) {
b47dc5ff
FM
1445 return new mod_lesson_file_info($browser, $course, $cm, $context, $areas, $filearea);
1446 }
1447
0a4abb73
SH
1448 $fs = get_file_storage();
1449 $filepath = is_null($filepath) ? '/' : $filepath;
1450 $filename = is_null($filename) ? '.' : $filename;
64f93798 1451 if (!$storedfile = $fs->get_file($context->id, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) {
0a4abb73
SH
1452 return null;
1453 }
b47dc5ff
FM
1454
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];
1463 }
1464 }
1465
1466 $urlbase = $CFG->wwwroot . '/pluginfile.php';
1467 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false);
0a4abb73 1468}
b1627a92
DC
1469
1470
1471/**
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
1476 */
b38e2e28 1477function lesson_page_type_list($pagetype, $parentcontext, $currentcontext) {
346a32a7
AD
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'));
b1627a92
DC
1482 return $module_pagetype;
1483}
684c3be7
MN
1484
1485/**
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.
1489 *
1490 * @param int $lessonid the lesson id
1491 * @param stdClass $context the context
1492 * @param int $draftitemid the draft item
1493 */
1494function lesson_update_media_file($lessonid, $context, $draftitemid) {
1495 global $DB;
1496
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));
1512 }
1513}
2b931458
DW
1514
1515/**
1516 * Get icon mapping for font-awesome.
1517 */
1518function mod_lesson_get_fontawesome_icon_map() {
1519 return [
1520 'mod_lesson:e/copy' => 'fa-clone',
1521 ];
1522}
635721f5
JL
1523
1524/*
1525 * Check if the module has any update that affects the current user since a given time.
1526 *
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
1532 */
1533function lesson_check_updates_since(cm_info $cm, $from, $filter = array()) {
1534 global $DB, $USER;
1535
1536 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1537
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 > ?)';
0a348387 1542 $params = array($cm->instance, $from, $from);
635721f5
JL
1543
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);
1548 }
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);
1553 }
1554
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);
1560
1561 $select = 'lessonid = ? AND userid = ? AND timeseen > ?';
1562 $params = array($cm->instance, $USER->id, $from);
1563
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);
1568 }
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);
1573 }
1574
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);
1580 }
1581
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);
1588 }
1589
0a348387
JL
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);
1594
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;
1601 }
1602 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1603 $select .= ' AND userid ' . $insql;
1604 $params = array_merge($params, $inparams);
1605 }
1606
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);
1611
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);
1616 }
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);
1621 }
1622
56da66ad
JL
1623 $select = 'lessonid = ? AND completed > ?';
1624 if (!empty($insql)) {
1625 $select .= ' AND userid ' . $insql;
1626 }
0a348387
JL
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);
1631 }
1632
56da66ad 1633 $select = 'lessonid = ? AND (starttime > ? OR lessontime > ? OR timemodifiedoffline > ?)';
0a348387 1634 $params = array($cm->instance, $from, $from, $from);
56da66ad
JL
1635 if (!empty($insql)) {
1636 $select .= ' AND userid ' . $insql;
1637 $params = array_merge($params, $inparams);
1638 }
0a348387
JL
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);
1643 }
1644 }
635721f5
JL
1645 return $updates;
1646}
8a8bd425
CB
1647
1648/**
59391e80
MN
1649 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1650 *
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.
8a8bd425 1653 *
e1cd93ce 1654 * @param calendar_event $event
8a8bd425 1655 * @param \core_calendar\action_factory $factory
01f96180 1656 * @return \core_calendar\local\event\entities\action_interface|null
8a8bd425 1657 */
e1cd93ce 1658function mod_lesson_core_calendar_provide_event_action(calendar_event $event,
8a8bd425 1659 \core_calendar\action_factory $factory) {
aa1cdff5 1660 global $DB, $CFG, $USER;
8a8bd425
CB
1661 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
1662
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));
1665
bfc8fbea
RW
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;
1669 }
1670
aa1cdff5
CB
1671 // Apply overrides.
1672 $lesson->update_effective_access($USER->id);
1673
8a8bd425
CB
1674 return $factory->create_instance(
1675 get_string('startlesson', 'lesson'),
1676 new \moodle_url('/mod/lesson/view.php', ['id' => $cm->id]),
1677 1,
1678 $lesson->is_accessible()
1679 );
1680}
b54bcddd
JD
1681
1682/**
1683 * Add a get_coursemodule_info function in case any lesson type wants to add 'extra' information
1684 * for the course (see resource).
1685 *
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.
1688 *
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).
1692 */
1693function lesson_get_coursemodule_info($coursemodule) {
1694 global $DB;
1695
1696 $dbparams = ['id' => $coursemodule->instance];
438c01d0 1697 $fields = 'id, name, intro, introformat, completionendreached, completiontimespent';
b54bcddd
JD
1698 if (!$lesson = $DB->get_record('lesson', $dbparams, $fields)) {
1699 return false;
1700 }
1701
1702 $result = new cached_cm_info();
23e5104a 1703 $result->name = $lesson->name;
b54bcddd 1704
438c01d0
MG
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);
1708 }
1709
b54bcddd
JD
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;
1714 }
1715
1716 return $result;
1717}
1718
1719/**
1720 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1721 *
7f53e8aa 1722 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
b54bcddd
JD
1723 * @return array $descriptions the array of descriptions for the custom rules.
1724 */
1725function mod_lesson_get_completion_active_rule_descriptions($cm) {
1726 // Values will be present in cm_info, and we assume these are up to date.
7f53e8aa 1727 if (empty($cm->customdata['customcompletionrules'])
b54bcddd
JD
1728 || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
1729 return [];
1730 }
1731
1732 $descriptions = [];
1733 foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
1734 switch ($key) {
1735 case 'completionendreached':
1736 if (empty($val)) {
1737 continue;
1738 }
1739 $descriptions[] = get_string('completionendreached_desc', 'lesson', $val);
1740 break;
1741 case 'completiontimespent':
1742 if (empty($val)) {
1743 continue;
1744 }
1745 $descriptions[] = get_string('completiontimespentdesc', 'lesson', format_time($val));
1746 break;
1747 default:
1748 break;
1749 }
1750 }
1751 return $descriptions;
1752}
f077e0af
SL
1753
1754/**
1755 * This function calculates the minimum and maximum cutoff values for the timestart of
1756 * the given event.
1757 *
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.
1761 *
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.
1764 *
1765 * A minimum and maximum cutoff return value will look like:
1766 * [
1767 * [1505704373, 'The due date must be after the start date'],
1768 * [1506741172, 'The due date must be before the cutoff date']
1769 * ]
1770 *
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
1774 */
1775function mod_lesson_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1776 $mindate = null;
1777 $maxdate = null;
1778
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')
1786 ];
1787 }
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')
1795 ];
1796 }
1797 }
1798
1799 return [$mindate, $maxdate];
1800}
1801
1802/**
1803 * This function will update the lesson module according to the
1804 * event that has been modified.
1805 *
1806 * It will set the available or deadline value of the lesson instance
1807 * according to the type of event provided.
1808 *
1809 * @throws \moodle_exception
1810 * @param \calendar_event $event
1811 * @param stdClass $lesson The module instance to get the range from
1812 */
1813function mod_lesson_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $lesson) {
1814 global $DB;
1815
1816 if (empty($event->instance) || $event->modulename != 'lesson') {
1817 return;
1818 }
1819
1820 if ($event->instance != $lesson->id) {
1821 return;
1822 }
1823
1824 if (!in_array($event->eventtype, [LESSON_EVENT_TYPE_OPEN, LESSON_EVENT_TYPE_CLOSE])) {
1825 return;
1826 }
1827
1828 $courseid = $event->courseid;
1829 $modulename = $event->modulename;
1830 $instanceid = $event->instance;
1831 $modified = false;
1832
1833 $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1834 $context = context_module::instance($coursemodule->id);
1835
1836 // The user does not have the capability to modify this activity.
1837 if (!has_capability('moodle/course:manageactivities', $context)) {
1838 return;
1839 }
1840
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;
1849 }
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;
1857 }
1858 }
1859
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();
1865 }
1866}