3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Standard library of functions and constants for lesson
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') ||
die();
29 define('LESSON_EVENT_TYPE_OPEN', 'open');
30 define('LESSON_EVENT_TYPE_CLOSE', 'close');
32 require_once(__DIR__
. '/deprecatedlib.php');
33 /* Do not include any libraries here! */
36 * Given an object containing all the necessary data,
37 * (defined by the form in mod_form.php) this function
38 * will create a new instance and return the id number
39 * of the new instance.
43 * @param object $lesson Lesson post data from the form
46 function lesson_add_instance($data, $mform) {
49 $cmid = $data->coursemodule
;
50 $draftitemid = $data->mediafile
;
51 $context = context_module
::instance($cmid);
53 lesson_process_pre_save($data);
55 unset($data->mediafile
);
56 $lessonid = $DB->insert_record("lesson", $data);
57 $data->id
= $lessonid;
59 lesson_update_media_file($lessonid, $context, $draftitemid);
61 lesson_process_post_save($data);
63 lesson_grade_item_update($data);
69 * Given an object containing all the necessary data,
70 * (defined by the form in mod_form.php) this function
71 * will update an existing instance with new data.
74 * @param object $lesson Lesson post data from the form
77 function lesson_update_instance($data, $mform) {
80 $data->id
= $data->instance
;
81 $cmid = $data->coursemodule
;
82 $draftitemid = $data->mediafile
;
83 $context = context_module
::instance($cmid);
85 lesson_process_pre_save($data);
87 unset($data->mediafile
);
88 $DB->update_record("lesson", $data);
90 lesson_update_media_file($data->id
, $context, $draftitemid);
92 lesson_process_post_save($data);
94 // update grade item definition
95 lesson_grade_item_update($data);
97 // update grades - TODO: do it only when grading style changes
98 lesson_update_grades($data, 0, false);
104 * This function updates the events associated to the lesson.
105 * If $override is non-zero, then it updates only the events
106 * associated with the specified override.
108 * @uses LESSON_MAX_EVENT_LENGTH
109 * @param object $lesson the lesson object.
110 * @param object $override (optional) limit to a specific override
112 function lesson_update_events($lesson, $override = null) {
115 require_once($CFG->dirroot
. '/mod/lesson/locallib.php');
116 require_once($CFG->dirroot
. '/calendar/lib.php');
118 // Load the old events relating to this lesson.
119 $conds = array('modulename' => 'lesson',
120 'instance' => $lesson->id
);
121 if (!empty($override)) {
122 // Only load events for this override.
123 if (isset($override->userid
)) {
124 $conds['userid'] = $override->userid
;
126 $conds['groupid'] = $override->groupid
;
129 $oldevents = $DB->get_records('event', $conds, 'id ASC');
131 // Now make a to-do list of all that needs to be updated.
132 if (empty($override)) {
133 // We are updating the primary settings for the lesson, so we need to add all the overrides.
134 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $lesson->id
), 'id ASC');
135 // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
136 // list contains the original (non-override) event for the module. If this is not included
137 // the logic below will end up updating the wrong row when we try to reconcile this $overrides
138 // list against the $oldevents list.
139 array_unshift($overrides, new stdClass());
141 // Just do the one override.
142 $overrides = array($override);
145 // Get group override priorities.
146 $grouppriorities = lesson_get_group_override_priorities($lesson->id
);
148 foreach ($overrides as $current) {
149 $groupid = isset($current->groupid
) ?
$current->groupid
: 0;
150 $userid = isset($current->userid
) ?
$current->userid
: 0;
151 $available = isset($current->available
) ?
$current->available
: $lesson->available
;
152 $deadline = isset($current->deadline
) ?
$current->deadline
: $lesson->deadline
;
154 // Only add open/close events for an override if they differ from the lesson default.
155 $addopen = empty($current->id
) ||
!empty($current->available
);
156 $addclose = empty($current->id
) ||
!empty($current->deadline
);
158 if (!empty($lesson->coursemodule
)) {
159 $cmid = $lesson->coursemodule
;
161 $cmid = get_coursemodule_from_instance('lesson', $lesson->id
, $lesson->course
)->id
;
164 $event = new stdClass();
165 $event->type
= !$deadline ? CALENDAR_EVENT_TYPE_ACTION
: CALENDAR_EVENT_TYPE_STANDARD
;
166 $event->description
= format_module_intro('lesson', $lesson, $cmid, false);
167 $event->format
= FORMAT_HTML
;
168 // Events module won't show user events when the courseid is nonzero.
169 $event->courseid
= ($userid) ?
0 : $lesson->course
;
170 $event->groupid
= $groupid;
171 $event->userid
= $userid;
172 $event->modulename
= 'lesson';
173 $event->instance
= $lesson->id
;
174 $event->timestart
= $available;
175 $event->timeduration
= max($deadline - $available, 0);
176 $event->timesort
= $available;
177 $event->visible
= instance_is_visible('lesson', $lesson);
178 $event->eventtype
= LESSON_EVENT_TYPE_OPEN
;
179 $event->priority
= null;
181 // Determine the event name and priority.
183 // Group override event.
184 $params = new stdClass();
185 $params->lesson
= $lesson->name
;
186 $params->group
= groups_get_group_name($groupid);
187 if ($params->group
=== false) {
188 // Group doesn't exist, just skip it.
191 $eventname = get_string('overridegroupeventname', 'lesson', $params);
192 // Set group override priority.
193 if ($grouppriorities !== null) {
194 $openpriorities = $grouppriorities['open'];
195 if (isset($openpriorities[$available])) {
196 $event->priority
= $openpriorities[$available];
199 } else if ($userid) {
200 // User override event.
201 $params = new stdClass();
202 $params->lesson
= $lesson->name
;
203 $eventname = get_string('overrideusereventname', 'lesson', $params);
204 // Set user override priority.
205 $event->priority
= CALENDAR_EVENT_USER_OVERRIDE_PRIORITY
;
208 $eventname = $lesson->name
;
211 if ($addopen or $addclose) {
212 // Separate start and end events.
213 $event->timeduration
= 0;
214 if ($available && $addopen) {
215 if ($oldevent = array_shift($oldevents)) {
216 $event->id
= $oldevent->id
;
220 $event->name
= get_string('lessoneventopens', 'lesson', $eventname);
221 // The method calendar_event::create will reuse a db record if the id field is set.
222 calendar_event
::create($event, false);
224 if ($deadline && $addclose) {
225 if ($oldevent = array_shift($oldevents)) {
226 $event->id
= $oldevent->id
;
230 $event->type
= CALENDAR_EVENT_TYPE_ACTION
;
231 $event->name
= get_string('lessoneventcloses', 'lesson', $eventname);
232 $event->timestart
= $deadline;
233 $event->timesort
= $deadline;
234 $event->eventtype
= LESSON_EVENT_TYPE_CLOSE
;
235 if ($groupid && $grouppriorities !== null) {
236 $closepriorities = $grouppriorities['close'];
237 if (isset($closepriorities[$deadline])) {
238 $event->priority
= $closepriorities[$deadline];
241 calendar_event
::create($event, false);
246 // Delete any leftover events.
247 foreach ($oldevents as $badevent) {
248 $badevent = calendar_event
::load($badevent);
254 * Calculates the priorities of timeopen and timeclose values for group overrides for a lesson.
256 * @param int $lessonid The lesson ID.
257 * @return array|null Array of group override priorities for open and close times. Null if there are no group overrides.
259 function lesson_get_group_override_priorities($lessonid) {
262 // Fetch group overrides.
263 $where = 'lessonid = :lessonid AND groupid IS NOT NULL';
264 $params = ['lessonid' => $lessonid];
265 $overrides = $DB->get_records_select('lesson_overrides', $where, $params, '', 'id, groupid, available, deadline');
271 $grouptimeclose = [];
272 foreach ($overrides as $override) {
273 if ($override->available
!== null && !in_array($override->available
, $grouptimeopen)) {
274 $grouptimeopen[] = $override->available
;
276 if ($override->deadline
!== null && !in_array($override->deadline
, $grouptimeclose)) {
277 $grouptimeclose[] = $override->deadline
;
281 // Sort open times in ascending manner. The earlier open time gets higher priority.
282 sort($grouptimeopen);
284 $opengrouppriorities = [];
286 foreach ($grouptimeopen as $timeopen) {
287 $opengrouppriorities[$timeopen] = $openpriority++
;
290 // Sort close times in descending manner. The later close time gets higher priority.
291 rsort($grouptimeclose);
293 $closegrouppriorities = [];
295 foreach ($grouptimeclose as $timeclose) {
296 $closegrouppriorities[$timeclose] = $closepriority++
;
300 'open' => $opengrouppriorities,
301 'close' => $closegrouppriorities
306 * This standard function will check all instances of this module
307 * and make sure there are up-to-date events created for each of them.
308 * If courseid = 0, then every lesson event in the site is checked, else
309 * only lesson events belonging to the course specified are checked.
310 * This function is used, in its new format, by restore_refresh_events()
312 * @param int $courseid
313 * @param int|stdClass $instance Lesson module instance or ID.
314 * @param int|stdClass $cm Course module object or ID (not used in this module).
317 function lesson_refresh_events($courseid = 0, $instance = null, $cm = null) {
320 // If we have instance information then we can just update the one event instead of updating all events.
321 if (isset($instance)) {
322 if (!is_object($instance)) {
323 $instance = $DB->get_record('lesson', array('id' => $instance), '*', MUST_EXIST
);
325 lesson_update_events($instance);
329 if ($courseid == 0) {
330 if (!$lessons = $DB->get_records('lesson')) {
334 if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) {
339 foreach ($lessons as $lesson) {
340 lesson_update_events($lesson);
347 * Given an ID of an instance of this module,
348 * this function will permanently delete the instance
349 * and any data that depends on it.
355 function lesson_delete_instance($id) {
357 require_once($CFG->dirroot
. '/mod/lesson/locallib.php');
359 $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST
);
360 $lesson = new lesson($lesson);
361 return $lesson->delete();
365 * Return a small object with summary information about what a
366 * user has done with a given particular instance of this module
367 * Used for user activity reports.
368 * $return->time = the time they did it
369 * $return->info = a short text description
372 * @param object $course
373 * @param object $user
375 * @param object $lesson
378 function lesson_user_outline($course, $user, $mod, $lesson) {
381 require_once("$CFG->libdir/gradelib.php");
382 $grades = grade_get_grades($course->id
, 'mod', 'lesson', $lesson->id
, $user->id
);
383 $return = new stdClass();
385 if (empty($grades->items
[0]->grades
)) {
386 $return->info
= get_string("nolessonattempts", "lesson");
388 $grade = reset($grades->items
[0]->grades
);
389 if (empty($grade->grade
)) {
391 // Check to see if it an ungraded / incomplete attempt.
394 WHERE lessonid = :lessonid
396 ORDER BY starttime DESC";
397 $params = array('lessonid' => $lesson->id
, 'userid' => $user->id
);
399 if ($attempts = $DB->get_records_sql($sql, $params, 0, 1)) {
400 $attempt = reset($attempts);
401 if ($attempt->completed
) {
402 $return->info
= get_string("completed", "lesson");
404 $return->info
= get_string("notyetcompleted", "lesson");
406 $return->time
= $attempt->lessontime
;
408 $return->info
= get_string("nolessonattempts", "lesson");
411 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
412 $return->info
= get_string('gradenoun') . ': ' . $grade->str_long_grade
;
414 $return->info
= get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
417 $return->time
= grade_get_date_for_user_grade($grade, $user);
424 * Print a detailed representation of what a user has done with
425 * a given particular instance of this module, for user activity reports.
428 * @param object $course
429 * @param object $user
431 * @param object $lesson
434 function lesson_user_complete($course, $user, $mod, $lesson) {
435 global $DB, $OUTPUT, $CFG;
437 require_once("$CFG->libdir/gradelib.php");
439 $grades = grade_get_grades($course->id
, 'mod', 'lesson', $lesson->id
, $user->id
);
441 // Display the grade and feedback.
442 if (empty($grades->items
[0]->grades
)) {
443 echo $OUTPUT->container(get_string("nolessonattempts", "lesson"));
445 $grade = reset($grades->items
[0]->grades
);
446 if (empty($grade->grade
)) {
447 // Check to see if it an ungraded / incomplete attempt.
450 WHERE lessonid = :lessonid
452 ORDER by starttime desc";
453 $params = array('lessonid' => $lesson->id
, 'userid' => $user->id
);
455 if ($attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE
)) {
456 if ($attempt->completed
) {
457 $status = get_string("completed", "lesson");
459 $status = get_string("notyetcompleted", "lesson");
462 $status = get_string("nolessonattempts", "lesson");
465 if (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
))) {
466 $status = get_string('gradenoun') . ': ' . $grade->str_long_grade
;
468 $status = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
472 // Display the grade or lesson status if there isn't one.
473 echo $OUTPUT->container($status);
475 if ($grade->str_feedback
&&
476 (!$grade->hidden ||
has_capability('moodle/grade:viewhidden', context_course
::instance($course->id
)))) {
477 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
481 // Display the lesson progress.
482 // Attempt, pages viewed, questions answered, correct answers, time.
483 $params = array ("lessonid" => $lesson->id
, "userid" => $user->id
);
484 $attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
485 $branches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
486 if (!empty($attempts) or !empty($branches)) {
487 echo $OUTPUT->box_start();
488 $table = new html_table();
490 $table->head
= array (get_string("attemptheader", "lesson"),
491 get_string("totalpagesviewedheader", "lesson"),
492 get_string("numberofpagesviewedheader", "lesson"),
493 get_string("numberofcorrectanswersheader", "lesson"),
495 $table->width
= "100%";
496 $table->align
= array ("center", "center", "center", "center", "center");
497 $table->size
= array ("*", "*", "*", "*", "*");
498 $table->cellpadding
= 2;
499 $table->cellspacing
= 0;
506 // Filter question pages (from lesson_attempts).
507 foreach ($attempts as $attempt) {
508 if ($attempt->retry
== $retry) {
511 if ($attempt->correct
) {
514 $timeseen = $attempt->timeseen
;
516 $table->data
[] = array($retry +
1, $npages, $nquestions, $ncorrect, userdate($timeseen));
520 if ($attempt->correct
) {
528 // Filter content pages (from lesson_branch).
529 foreach ($branches as $branch) {
530 if ($branch->retry
== $retry) {
533 $timeseen = $branch->timeseen
;
535 $table->data
[] = array($retry +
1, $npages, $nquestions, $ncorrect, userdate($timeseen));
541 $table->data
[] = array($retry +
1, $npages, $nquestions, $ncorrect, userdate($timeseen));
543 echo html_writer
::table($table);
544 echo $OUTPUT->box_end();
551 * @deprecated since Moodle 3.3, when the block_course_overview block was removed.
553 function lesson_print_overview() {
554 throw new coding_exception('lesson_print_overview() can not be used any more and is obsolete.');
558 * Function to be run periodically according to the moodle cron
559 * This function searches for things that need to be done, such
560 * as sending out mail, toggling flags etc ...
564 function lesson_cron () {
571 * Return grade for given user or all users.
575 * @param int $lessonid id of lesson
576 * @param int $userid optional user id, 0 means all users
577 * @return array array of grades, false if none
579 function lesson_get_user_grades($lesson, $userid=0) {
582 $params = array("lessonid" => $lesson->id
,"lessonid2" => $lesson->id
);
584 if (!empty($userid)) {
585 $params["userid"] = $userid;
586 $params["userid2"] = $userid;
587 $user = "AND u.id = :userid";
588 $fuser = "AND uu.id = :userid2";
595 if ($lesson->retake
) {
596 if ($lesson->usemaxgrade
) {
597 $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade
598 FROM {user} u, {lesson_grades} g
599 WHERE u.id = g.userid AND g.lessonid = :lessonid
603 $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade
604 FROM {user} u, {lesson_grades} g
605 WHERE u.id = g.userid AND g.lessonid = :lessonid
609 unset($params['lessonid2']);
610 unset($params['userid2']);
612 // use only first attempts (with lowest id in lesson_grades table)
613 $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted
614 FROM {user} uu, {lesson_grades} gg
615 WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2
619 $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade
620 FROM {user} u, {lesson_grades} g, ($firstonly) f
621 WHERE u.id = g.userid AND g.lessonid = :lessonid
622 AND g.id = f.firstcompleted AND g.userid=f.userid
626 return $DB->get_records_sql($sql, $params);
630 * Update grades in central gradebook
633 * @param object $lesson
634 * @param int $userid specific user only, 0 means all
635 * @param bool $nullifnone
637 function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
639 require_once($CFG->libdir
.'/gradelib.php');
641 if ($lesson->grade
== 0 ||
$lesson->practice
) {
642 lesson_grade_item_update($lesson);
644 } else if ($grades = lesson_get_user_grades($lesson, $userid)) {
645 lesson_grade_item_update($lesson, $grades);
647 } else if ($userid and $nullifnone) {
648 $grade = new stdClass();
649 $grade->userid
= $userid;
650 $grade->rawgrade
= null;
651 lesson_grade_item_update($lesson, $grade);
654 lesson_grade_item_update($lesson);
659 * Create grade item for given lesson
662 * @uses GRADE_TYPE_VALUE
663 * @uses GRADE_TYPE_NONE
664 * @param object $lesson object with extra cmidnumber
665 * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
666 * @return int 0 if ok, error code otherwise
668 function lesson_grade_item_update($lesson, $grades=null) {
670 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
671 require_once($CFG->libdir
.'/gradelib.php');
674 if (property_exists($lesson, 'cmidnumber')) { //it may not be always present
675 $params = array('itemname'=>$lesson->name
, 'idnumber'=>$lesson->cmidnumber
);
677 $params = array('itemname'=>$lesson->name
);
680 if (!$lesson->practice
and $lesson->grade
> 0) {
681 $params['gradetype'] = GRADE_TYPE_VALUE
;
682 $params['grademax'] = $lesson->grade
;
683 $params['grademin'] = 0;
684 } else if (!$lesson->practice
and $lesson->grade
< 0) {
685 $params['gradetype'] = GRADE_TYPE_SCALE
;
686 $params['scaleid'] = -$lesson->grade
;
688 // Make sure current grade fetched correctly from $grades
689 $currentgrade = null;
690 if (!empty($grades)) {
691 if (is_array($grades)) {
692 $currentgrade = reset($grades);
694 $currentgrade = $grades;
698 // When converting a score to a scale, use scale's grade maximum to calculate it.
699 if (!empty($currentgrade) && $currentgrade->rawgrade
!== null) {
700 $grade = grade_get_grades($lesson->course
, 'mod', 'lesson', $lesson->id
, $currentgrade->userid
);
701 $params['grademax'] = reset($grade->items
)->grademax
;
704 $params['gradetype'] = GRADE_TYPE_NONE
;
707 if ($grades === 'reset') {
708 $params['reset'] = true;
710 } else if (!empty($grades)) {
711 // Need to calculate raw grade (Note: $grades has many forms)
712 if (is_object($grades)) {
713 $grades = array($grades->userid
=> $grades);
714 } else if (array_key_exists('userid', $grades)) {
715 $grades = array($grades['userid'] => $grades);
717 foreach ($grades as $key => $grade) {
718 if (!is_array($grade)) {
719 $grades[$key] = $grade = (array) $grade;
721 //check raw grade isnt null otherwise we erroneously insert a grade of 0
722 if ($grade['rawgrade'] !== null) {
723 $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100);
725 //setting rawgrade to null just in case user is deleting a grade
726 $grades[$key]['rawgrade'] = null;
731 return grade_update('mod/lesson', $lesson->course
, 'mod', 'lesson', $lesson->id
, 0, $grades, $params);
735 * List the actions that correspond to a view of this module.
736 * This is used by the participation report.
738 * Note: This is not used by new logging system. Event with
739 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
740 * be considered as view action.
744 function lesson_get_view_actions() {
745 return array('view','view all');
749 * List the actions that correspond to a post of this module.
750 * This is used by the participation report.
752 * Note: This is not used by new logging system. Event with
753 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
754 * will be considered as post action.
758 function lesson_get_post_actions() {
759 return array('end','start');
763 * Runs any processes that must run before
764 * a lesson insert/update
767 * @param object $lesson Lesson form data
770 function lesson_process_pre_save(&$lesson) {
773 $lesson->timemodified
= time();
775 if (empty($lesson->timelimit
)) {
776 $lesson->timelimit
= 0;
778 if (empty($lesson->timespent
) or !is_numeric($lesson->timespent
) or $lesson->timespent
< 0) {
779 $lesson->timespent
= 0;
781 if (!isset($lesson->completed
)) {
782 $lesson->completed
= 0;
784 if (empty($lesson->gradebetterthan
) or !is_numeric($lesson->gradebetterthan
) or $lesson->gradebetterthan
< 0) {
785 $lesson->gradebetterthan
= 0;
786 } else if ($lesson->gradebetterthan
> 100) {
787 $lesson->gradebetterthan
= 100;
790 if (empty($lesson->width
)) {
791 $lesson->width
= 640;
793 if (empty($lesson->height
)) {
794 $lesson->height
= 480;
796 if (empty($lesson->bgcolor
)) {
797 $lesson->bgcolor
= '#FFFFFF';
800 // Conditions for dependency
801 $conditions = new stdClass
;
802 $conditions->timespent
= $lesson->timespent
;
803 $conditions->completed
= $lesson->completed
;
804 $conditions->gradebetterthan
= $lesson->gradebetterthan
;
805 $lesson->conditions
= serialize($conditions);
806 unset($lesson->timespent
);
807 unset($lesson->completed
);
808 unset($lesson->gradebetterthan
);
810 if (empty($lesson->password
)) {
811 unset($lesson->password
);
816 * Runs any processes that must be run
817 * after a lesson insert/update
820 * @param object $lesson Lesson form data
823 function lesson_process_post_save(&$lesson) {
824 // Update the events relating to this lesson.
825 lesson_update_events($lesson);
826 $completionexpected = (!empty($lesson->completionexpected
)) ?
$lesson->completionexpected
: null;
827 \core_completion\api
::update_completion_date_event($lesson->coursemodule
, 'lesson', $lesson, $completionexpected);
832 * Implementation of the function for printing the form elements that control
833 * whether the course reset functionality affects the lesson.
835 * @param MoodleQuickForm $mform form passed by reference
837 function lesson_reset_course_form_definition(&$mform) {
838 $mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson'));
839 $mform->addElement('static', 'lessondelete', get_string('delete'));
840 $mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts', 'lesson'));
841 $mform->addElement('advcheckbox', 'reset_lesson_user_overrides',
842 get_string('removealluseroverrides', 'lesson'));
843 $mform->addElement('advcheckbox', 'reset_lesson_group_overrides',
844 get_string('removeallgroupoverrides', 'lesson'));
848 * Course reset form defaults.
849 * @param object $course
852 function lesson_reset_course_form_defaults($course) {
853 return array('reset_lesson' => 1,
854 'reset_lesson_group_overrides' => 1,
855 'reset_lesson_user_overrides' => 1);
859 * Removes all grades from gradebook
863 * @param int $courseid
864 * @param string optional type
866 function lesson_reset_gradebook($courseid, $type='') {
869 $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
870 FROM {lesson} l, {course_modules} cm, {modules} m
871 WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course";
872 $params = array ("course" => $courseid);
873 if ($lessons = $DB->get_records_sql($sql,$params)) {
874 foreach ($lessons as $lesson) {
875 lesson_grade_item_update($lesson, 'reset');
881 * Actual implementation of the reset course functionality, delete all the
882 * lesson attempts for course $data->courseid.
886 * @param object $data the data submitted from the reset course.
887 * @return array status array
889 function lesson_reset_userdata($data) {
892 $componentstr = get_string('modulenameplural', 'lesson');
895 if (!empty($data->reset_lesson
)) {
896 $lessonssql = "SELECT l.id
898 WHERE l.course=:course";
900 $params = ["course" => $data->courseid
];
901 $lessons = $DB->get_records_sql($lessonssql, $params);
903 // Get rid of attempts files.
904 $fs = get_file_storage();
906 foreach ($lessons as $lessonid => $unused) {
907 if (!$cm = get_coursemodule_from_instance('lesson', $lessonid)) {
910 $context = context_module
::instance($cm->id
);
911 $fs->delete_area_files($context->id
, 'mod_lesson', 'essay_responses');
912 $fs->delete_area_files($context->id
, 'mod_lesson', 'essay_answers');
916 $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params);
917 $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params);
918 $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params);
919 $DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params);
921 // Remove all grades from gradebook.
922 if (empty($data->reset_gradebook_grades
)) {
923 lesson_reset_gradebook($data->courseid
);
927 'component' => $componentstr,
928 'item' => get_string('deleteallattempts', 'lesson'),
933 $purgeoverrides = false;
935 // Remove user overrides.
936 if (!empty($data->reset_lesson_user_overrides
)) {
937 $DB->delete_records_select('lesson_overrides',
938 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND userid IS NOT NULL', [$data->courseid
]);
940 'component' => $componentstr,
941 'item' => get_string('useroverrides', 'lesson'),
944 $purgeoverrides = true;
946 // Remove group overrides.
947 if (!empty($data->reset_lesson_group_overrides
)) {
948 $DB->delete_records_select('lesson_overrides',
949 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND groupid IS NOT NULL', [$data->courseid
]);
951 'component' => $componentstr,
952 'item' => get_string('groupoverrides', 'lesson'),
955 $purgeoverrides = true;
957 // Updating dates - shift may be negative too.
958 if ($data->timeshift
) {
959 $DB->execute("UPDATE {lesson_overrides}
960 SET available = available + ?
961 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
962 AND available <> 0", [$data->timeshift
, $data->courseid
]);
963 $DB->execute("UPDATE {lesson_overrides}
964 SET deadline = deadline + ?
965 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
966 AND deadline <> 0", [$data->timeshift
, $data->courseid
]);
968 $purgeoverrides = true;
970 // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
972 shift_course_mod_dates('lesson', ['available', 'deadline'], $data->timeshift
, $data->courseid
);
974 'component' => $componentstr,
975 'item' => get_string('date'),
980 if ($purgeoverrides) {
981 cache
::make('mod_lesson', 'overrides')->purge();
988 * @uses FEATURE_GROUPS
989 * @uses FEATURE_GROUPINGS
990 * @uses FEATURE_MOD_INTRO
991 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
992 * @uses FEATURE_GRADE_HAS_GRADE
993 * @uses FEATURE_GRADE_OUTCOMES
994 * @param string $feature FEATURE_xx constant for requested feature
995 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
997 function lesson_supports($feature) {
1001 case FEATURE_GROUPINGS
:
1003 case FEATURE_MOD_INTRO
:
1005 case FEATURE_COMPLETION_TRACKS_VIEWS
:
1007 case FEATURE_GRADE_HAS_GRADE
:
1009 case FEATURE_COMPLETION_HAS_RULES
:
1011 case FEATURE_GRADE_OUTCOMES
:
1013 case FEATURE_BACKUP_MOODLE2
:
1015 case FEATURE_SHOW_DESCRIPTION
:
1017 case FEATURE_MOD_PURPOSE
:
1018 return MOD_PURPOSE_INTERACTIVECONTENT
;
1025 * This function extends the settings navigation block for the site.
1027 * It is safe to rely on PAGE here as we will only ever be within the module
1028 * context when this is called
1030 * @param settings_navigation $settings
1031 * @param navigation_node $lessonnode
1033 function lesson_extend_settings_navigation(settings_navigation
$settings, navigation_node
$lessonnode) {
1034 // We want to add these new nodes after the Edit settings node, and before the
1035 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1036 $keys = $lessonnode->get_children_key_list();
1038 $i = array_search('modedit', $keys);
1039 if ($i === false and array_key_exists(0, $keys)) {
1040 $beforekey = $keys[0];
1041 } else if (array_key_exists($i +
1, $keys)) {
1042 $beforekey = $keys[$i +
1];
1045 if (has_capability('mod/lesson:manageoverrides', $settings->get_page()->cm
->context
)) {
1046 $url = new moodle_url('/mod/lesson/overrides.php', ['cmid' => $settings->get_page()->cm
->id
, 'mode' => 'user']);
1047 $node = navigation_node
::create(get_string('overrides', 'lesson'), $url,
1048 navigation_node
::TYPE_SETTING
, null, 'mod_lesson_useroverrides');
1049 $lessonnode->add_node($node, $beforekey);
1052 if (has_capability('mod/lesson:viewreports', $settings->get_page()->cm
->context
)) {
1053 $reportsnode = $lessonnode->add(
1054 get_string('reports', 'lesson'),
1055 new moodle_url('/mod/lesson/report.php', ['id' => $settings->get_page()->cm
->id
,
1056 'action' => 'reportoverview'])
1062 * Get list of available import or export formats
1064 * Copied and modified from lib/questionlib.php
1066 * @param string $type 'import' if import list, otherwise export list assumed
1067 * @return array sorted list of import/export formats available
1069 function lesson_get_import_export_formats($type) {
1071 $fileformats = core_component
::get_plugin_list("qformat");
1073 $fileformatname=array();
1074 foreach ($fileformats as $fileformat=>$fdir) {
1075 $format_file = "$fdir/format.php";
1076 if (file_exists($format_file) ) {
1077 require_once($format_file);
1081 $classname = "qformat_$fileformat";
1082 $format_class = new $classname();
1083 if ($type=='import') {
1084 $provided = $format_class->provide_import();
1086 $provided = $format_class->provide_export();
1089 $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat);
1092 natcasesort($fileformatnames);
1094 return $fileformatnames;
1098 * Serves the lesson attachments. Implements needed access control ;-)
1100 * @package mod_lesson
1102 * @param stdClass $course course object
1103 * @param stdClass $cm course module object
1104 * @param stdClass $context context object
1105 * @param string $filearea file area
1106 * @param array $args extra arguments
1107 * @param bool $forcedownload whether or not force download
1108 * @param array $options additional options affecting the file serving
1109 * @return bool false if file not found, does not return if found - justsend the file
1111 function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1114 if ($context->contextlevel
!= CONTEXT_MODULE
) {
1118 $fileareas = lesson_get_file_areas();
1119 if (!array_key_exists($filearea, $fileareas)) {
1123 if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance
))) {
1127 require_course_login($course, true, $cm);
1129 if ($filearea === 'page_contents') {
1130 $pageid = (int)array_shift($args);
1131 if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) {
1134 $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args);
1136 } else if ($filearea === 'page_answers' ||
$filearea === 'page_responses') {
1137 $itemid = (int)array_shift($args);
1138 if (!$pageanswers = $DB->get_record('lesson_answers', array('id' => $itemid))) {
1141 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1143 } else if ($filearea === 'essay_responses' ||
$filearea === 'essay_answers') {
1144 $itemid = (int)array_shift($args);
1145 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $itemid))) {
1148 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1150 } else if ($filearea === 'mediafile') {
1151 if (count($args) > 1) {
1152 // Remove the itemid when it appears to be part of the arguments. If there is only one argument
1153 // then it is surely the file name. The itemid is sometimes used to prevent browser caching.
1156 $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args);
1162 $fs = get_file_storage();
1163 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1167 // finally send the file
1168 send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security!
1172 * Returns an array of file areas
1174 * @package mod_lesson
1176 * @return array a list of available file areas
1178 function lesson_get_file_areas() {
1180 $areas['page_contents'] = get_string('pagecontents', 'mod_lesson');
1181 $areas['mediafile'] = get_string('mediafile', 'mod_lesson');
1182 $areas['page_answers'] = get_string('pageanswers', 'mod_lesson');
1183 $areas['page_responses'] = get_string('pageresponses', 'mod_lesson');
1184 $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson');
1185 $areas['essay_answers'] = get_string('essayresponses', 'mod_lesson');
1190 * Returns a file_info_stored object for the file being requested here
1192 * @package mod_lesson
1194 * @global stdClass $CFG
1195 * @param file_browser $browser file browser instance
1196 * @param array $areas file areas
1197 * @param stdClass $course course object
1198 * @param stdClass $cm course module object
1199 * @param stdClass $context context object
1200 * @param string $filearea file area
1201 * @param int $itemid item ID
1202 * @param string $filepath file path
1203 * @param string $filename file name
1204 * @return file_info_stored
1206 function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
1209 if (!has_capability('moodle/course:managefiles', $context)) {
1210 // No peaking here for students!
1214 // Mediafile area does not have sub directories, so let's select the default itemid to prevent
1215 // the user from selecting a directory to access the mediafile content.
1216 if ($filearea == 'mediafile' && is_null($itemid)) {
1220 if (is_null($itemid)) {
1221 return new mod_lesson_file_info($browser, $course, $cm, $context, $areas, $filearea);
1224 $fs = get_file_storage();
1225 $filepath = is_null($filepath) ?
'/' : $filepath;
1226 $filename = is_null($filename) ?
'.' : $filename;
1227 if (!$storedfile = $fs->get_file($context->id
, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) {
1231 $itemname = $filearea;
1232 if ($filearea == 'page_contents') {
1233 $itemname = $DB->get_field('lesson_pages', 'title', array('lessonid' => $cm->instance
, 'id' => $itemid));
1234 $itemname = format_string($itemname, true, array('context' => $context));
1236 $areas = lesson_get_file_areas();
1237 if (isset($areas[$filearea])) {
1238 $itemname = $areas[$filearea];
1242 $urlbase = $CFG->wwwroot
. '/pluginfile.php';
1243 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false);
1248 * Return a list of page types
1249 * @param string $pagetype current page type
1250 * @param stdClass $parentcontext Block's parent context
1251 * @param stdClass $currentcontext Current context of block
1253 function lesson_page_type_list($pagetype, $parentcontext, $currentcontext) {
1254 $module_pagetype = array(
1255 'mod-lesson-*'=>get_string('page-mod-lesson-x', 'lesson'),
1256 'mod-lesson-view'=>get_string('page-mod-lesson-view', 'lesson'),
1257 'mod-lesson-edit'=>get_string('page-mod-lesson-edit', 'lesson'));
1258 return $module_pagetype;
1262 * Update the lesson activity to include any file
1263 * that was uploaded, or if there is none, set the
1264 * mediafile field to blank.
1266 * @param int $lessonid the lesson id
1267 * @param stdClass $context the context
1268 * @param int $draftitemid the draft item
1270 function lesson_update_media_file($lessonid, $context, $draftitemid) {
1273 // Set the filestorage object.
1274 $fs = get_file_storage();
1275 // Save the file if it exists that is currently in the draft area.
1276 file_save_draft_area_files($draftitemid, $context->id
, 'mod_lesson', 'mediafile', 0);
1277 // Get the file if it exists.
1278 $files = $fs->get_area_files($context->id
, 'mod_lesson', 'mediafile', 0, 'itemid, filepath, filename', false);
1279 // Check that there is a file to process.
1280 if (count($files) == 1) {
1281 // Get the first (and only) file.
1282 $file = reset($files);
1283 // Set the mediafile column in the lessons table.
1284 $DB->set_field('lesson', 'mediafile', '/' . $file->get_filename(), array('id' => $lessonid));
1286 // Set the mediafile column in the lessons table.
1287 $DB->set_field('lesson', 'mediafile', '', array('id' => $lessonid));
1292 * Get icon mapping for font-awesome.
1294 function mod_lesson_get_fontawesome_icon_map() {
1296 'mod_lesson:e/copy' => 'fa-clone',
1301 * Check if the module has any update that affects the current user since a given time.
1303 * @param cm_info $cm course module data
1304 * @param int $from the time to check updates from
1305 * @param array $filter if we need to check only specific updates
1306 * @return stdClass an object with the different type of areas indicating if they were updated or not
1309 function lesson_check_updates_since(cm_info
$cm, $from, $filter = array()) {
1312 $updates = course_check_module_updates_since($cm, $from, array(), $filter);
1314 // Check if there are new pages or answers in the lesson.
1315 $updates->pages
= (object) array('updated' => false);
1316 $updates->answers
= (object) array('updated' => false);
1317 $select = 'lessonid = ? AND (timecreated > ? OR timemodified > ?)';
1318 $params = array($cm->instance
, $from, $from);
1320 $pages = $DB->get_records_select('lesson_pages', $select, $params, '', 'id');
1321 if (!empty($pages)) {
1322 $updates->pages
->updated
= true;
1323 $updates->pages
->itemids
= array_keys($pages);
1325 $answers = $DB->get_records_select('lesson_answers', $select, $params, '', 'id');
1326 if (!empty($answers)) {
1327 $updates->answers
->updated
= true;
1328 $updates->answers
->itemids
= array_keys($answers);
1331 // Check for new question attempts, grades, pages viewed and timers.
1332 $updates->questionattempts
= (object) array('updated' => false);
1333 $updates->grades
= (object) array('updated' => false);
1334 $updates->pagesviewed
= (object) array('updated' => false);
1335 $updates->timers
= (object) array('updated' => false);
1337 $select = 'lessonid = ? AND userid = ? AND timeseen > ?';
1338 $params = array($cm->instance
, $USER->id
, $from);
1340 $questionattempts = $DB->get_records_select('lesson_attempts', $select, $params, '', 'id');
1341 if (!empty($questionattempts)) {
1342 $updates->questionattempts
->updated
= true;
1343 $updates->questionattempts
->itemids
= array_keys($questionattempts);
1345 $pagesviewed = $DB->get_records_select('lesson_branch', $select, $params, '', 'id');
1346 if (!empty($pagesviewed)) {
1347 $updates->pagesviewed
->updated
= true;
1348 $updates->pagesviewed
->itemids
= array_keys($pagesviewed);
1351 $select = 'lessonid = ? AND userid = ? AND completed > ?';
1352 $grades = $DB->get_records_select('lesson_grades', $select, $params, '', 'id');
1353 if (!empty($grades)) {
1354 $updates->grades
->updated
= true;
1355 $updates->grades
->itemids
= array_keys($grades);
1358 $select = 'lessonid = ? AND userid = ? AND (starttime > ? OR lessontime > ? OR timemodifiedoffline > ?)';
1359 $params = array($cm->instance
, $USER->id
, $from, $from, $from);
1360 $timers = $DB->get_records_select('lesson_timer', $select, $params, '', 'id');
1361 if (!empty($timers)) {
1362 $updates->timers
->updated
= true;
1363 $updates->timers
->itemids
= array_keys($timers);
1366 // Now, teachers should see other students updates.
1367 if (has_capability('mod/lesson:viewreports', $cm->context
)) {
1368 $select = 'lessonid = ? AND timeseen > ?';
1369 $params = array($cm->instance
, $from);
1373 if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS
) {
1374 $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1375 if (empty($groupusers)) {
1378 list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
1379 $select .= ' AND userid ' . $insql;
1380 $params = array_merge($params, $inparams);
1383 $updates->userquestionattempts
= (object) array('updated' => false);
1384 $updates->usergrades
= (object) array('updated' => false);
1385 $updates->userpagesviewed
= (object) array('updated' => false);
1386 $updates->usertimers
= (object) array('updated' => false);
1388 $questionattempts = $DB->get_records_select('lesson_attempts', $select, $params, '', 'id');
1389 if (!empty($questionattempts)) {
1390 $updates->userquestionattempts
->updated
= true;
1391 $updates->userquestionattempts
->itemids
= array_keys($questionattempts);
1393 $pagesviewed = $DB->get_records_select('lesson_branch', $select, $params, '', 'id');
1394 if (!empty($pagesviewed)) {
1395 $updates->userpagesviewed
->updated
= true;
1396 $updates->userpagesviewed
->itemids
= array_keys($pagesviewed);
1399 $select = 'lessonid = ? AND completed > ?';
1400 if (!empty($insql)) {
1401 $select .= ' AND userid ' . $insql;
1403 $grades = $DB->get_records_select('lesson_grades', $select, $params, '', 'id');
1404 if (!empty($grades)) {
1405 $updates->usergrades
->updated
= true;
1406 $updates->usergrades
->itemids
= array_keys($grades);
1409 $select = 'lessonid = ? AND (starttime > ? OR lessontime > ? OR timemodifiedoffline > ?)';
1410 $params = array($cm->instance
, $from, $from, $from);
1411 if (!empty($insql)) {
1412 $select .= ' AND userid ' . $insql;
1413 $params = array_merge($params, $inparams);
1415 $timers = $DB->get_records_select('lesson_timer', $select, $params, '', 'id');
1416 if (!empty($timers)) {
1417 $updates->usertimers
->updated
= true;
1418 $updates->usertimers
->itemids
= array_keys($timers);
1425 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1427 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1428 * is not displayed on the block.
1430 * @param calendar_event $event
1431 * @param \core_calendar\action_factory $factory
1432 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1433 * @return \core_calendar\local\event\entities\action_interface|null
1435 function mod_lesson_core_calendar_provide_event_action(calendar_event
$event,
1436 \core_calendar\action_factory
$factory,
1438 global $DB, $CFG, $USER;
1439 require_once($CFG->dirroot
. '/mod/lesson/locallib.php');
1442 $userid = $USER->id
;
1445 $cm = get_fast_modinfo($event->courseid
, $userid)->instances
['lesson'][$event->instance
];
1447 if (!$cm->uservisible
) {
1448 // The module is not visible to the user for any reason.
1452 $completion = new \
completion_info($cm->get_course());
1454 $completiondata = $completion->get_data($cm, false, $userid);
1456 if ($completiondata->completionstate
!= COMPLETION_INCOMPLETE
) {
1460 $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance
), '*', MUST_EXIST
));
1462 if ($lesson->count_user_retries($userid)) {
1463 // If the user has attempted the lesson then there is no further action for the user.
1468 $lesson->update_effective_access($userid);
1470 if (!$lesson->is_participant($userid)) {
1471 // If the user is not a participant then they have
1472 // no action to take. This will filter out the events for teachers.
1476 return $factory->create_instance(
1477 get_string('startlesson', 'lesson'),
1478 new \
moodle_url('/mod/lesson/view.php', ['id' => $cm->id
]),
1480 $lesson->is_accessible()
1485 * Add a get_coursemodule_info function in case any lesson type wants to add 'extra' information
1486 * for the course (see resource).
1488 * Given a course_module object, this function returns any "extra" information that may be needed
1489 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1491 * @param stdClass $coursemodule The coursemodule object (record).
1492 * @return cached_cm_info An object on information that the courses
1493 * will know about (most noticeably, an icon).
1495 function lesson_get_coursemodule_info($coursemodule) {
1498 $dbparams = ['id' => $coursemodule->instance
];
1499 $fields = 'id, name, intro, introformat, completionendreached, completiontimespent, available, deadline';
1500 if (!$lesson = $DB->get_record('lesson', $dbparams, $fields)) {
1504 $result = new cached_cm_info();
1505 $result->name
= $lesson->name
;
1507 if ($coursemodule->showdescription
) {
1508 // Convert intro to html. Do not filter cached version, filters run at display time.
1509 $result->content
= format_module_intro('lesson', $lesson, $coursemodule->id
, false);
1512 // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
1513 if ($coursemodule->completion
== COMPLETION_TRACKING_AUTOMATIC
) {
1514 $result->customdata
['customcompletionrules']['completionendreached'] = $lesson->completionendreached
;
1515 $result->customdata
['customcompletionrules']['completiontimespent'] = $lesson->completiontimespent
;
1518 // Populate some other values that can be used in calendar or on dashboard.
1519 if ($lesson->available
) {
1520 $result->customdata
['available'] = $lesson->available
;
1522 if ($lesson->deadline
) {
1523 $result->customdata
['deadline'] = $lesson->deadline
;
1530 * Sets dynamic information about a course module
1532 * This function is called from cm_info when displaying the module
1534 * @param cm_info $cm
1536 function mod_lesson_cm_info_dynamic(cm_info
$cm) {
1539 $cache = cache
::make('mod_lesson', 'overrides');
1540 $override = $cache->get("{$cm->instance}_u_{$USER->id}");
1543 $override = (object) [
1544 'available' => null,
1549 // No need to look for group overrides if there are user overrides for both available and deadline.
1550 if (is_null($override->available
) ||
is_null($override->deadline
)) {
1553 $groupings = groups_get_user_groups($cm->course
, $USER->id
);
1554 foreach ($groupings[0] as $groupid) {
1555 $groupoverride = $cache->get("{$cm->instance}_g_{$groupid}");
1556 if (isset($groupoverride->available
)) {
1557 $availables[] = $groupoverride->available
;
1559 if (isset($groupoverride->deadline
)) {
1560 $deadlines[] = $groupoverride->deadline
;
1563 // If there is a user override for a setting, ignore the group override.
1564 if (is_null($override->available
) && count($availables)) {
1565 $override->available
= min($availables);
1567 if (is_null($override->deadline
) && count($deadlines)) {
1568 if (in_array(0, $deadlines)) {
1569 $override->deadline
= 0;
1571 $override->deadline
= max($deadlines);
1576 // Populate some other values that can be used in calendar or on dashboard.
1577 if (!is_null($override->available
)) {
1578 $cm->override_customdata('available', $override->available
);
1580 if (!is_null($override->deadline
)) {
1581 $cm->override_customdata('deadline', $override->deadline
);
1586 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
1588 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
1589 * @return array $descriptions the array of descriptions for the custom rules.
1591 function mod_lesson_get_completion_active_rule_descriptions($cm) {
1592 // Values will be present in cm_info, and we assume these are up to date.
1593 if (empty($cm->customdata
['customcompletionrules'])
1594 ||
$cm->completion
!= COMPLETION_TRACKING_AUTOMATIC
) {
1599 foreach ($cm->customdata
['customcompletionrules'] as $key => $val) {
1601 case 'completionendreached':
1603 $descriptions[] = get_string('completionendreached_desc', 'lesson', $val);
1606 case 'completiontimespent':
1608 $descriptions[] = get_string('completiontimespentdesc', 'lesson', format_time($val));
1615 return $descriptions;
1619 * This function calculates the minimum and maximum cutoff values for the timestart of
1622 * It will return an array with two values, the first being the minimum cutoff value and
1623 * the second being the maximum cutoff value. Either or both values can be null, which
1624 * indicates there is no minimum or maximum, respectively.
1626 * If a cutoff is required then the function must return an array containing the cutoff
1627 * timestamp and error string to display to the user if the cutoff value is violated.
1629 * A minimum and maximum cutoff return value will look like:
1631 * [1505704373, 'The due date must be after the start date'],
1632 * [1506741172, 'The due date must be before the cutoff date']
1635 * @param calendar_event $event The calendar event to get the time range for
1636 * @param stdClass $instance The module instance to get the range from
1639 function mod_lesson_core_calendar_get_valid_event_timestart_range(\calendar_event
$event, \stdClass
$instance) {
1643 if ($event->eventtype
== LESSON_EVENT_TYPE_OPEN
) {
1644 // The start time of the open event can't be equal to or after the
1645 // close time of the lesson activity.
1646 if (!empty($instance->deadline
)) {
1648 $instance->deadline
,
1649 get_string('openafterclose', 'lesson')
1652 } else if ($event->eventtype
== LESSON_EVENT_TYPE_CLOSE
) {
1653 // The start time of the close event can't be equal to or earlier than the
1654 // open time of the lesson activity.
1655 if (!empty($instance->available
)) {
1657 $instance->available
,
1658 get_string('closebeforeopen', 'lesson')
1663 return [$mindate, $maxdate];
1667 * This function will update the lesson module according to the
1668 * event that has been modified.
1670 * It will set the available or deadline value of the lesson instance
1671 * according to the type of event provided.
1673 * @throws \moodle_exception
1674 * @param \calendar_event $event
1675 * @param stdClass $lesson The module instance to get the range from
1677 function mod_lesson_core_calendar_event_timestart_updated(\calendar_event
$event, \stdClass
$lesson) {
1680 if (empty($event->instance
) ||
$event->modulename
!= 'lesson') {
1684 if ($event->instance
!= $lesson->id
) {
1688 if (!in_array($event->eventtype
, [LESSON_EVENT_TYPE_OPEN
, LESSON_EVENT_TYPE_CLOSE
])) {
1692 $courseid = $event->courseid
;
1693 $modulename = $event->modulename
;
1694 $instanceid = $event->instance
;
1697 $coursemodule = get_fast_modinfo($courseid)->instances
[$modulename][$instanceid];
1698 $context = context_module
::instance($coursemodule->id
);
1700 // The user does not have the capability to modify this activity.
1701 if (!has_capability('moodle/course:manageactivities', $context)) {
1705 if ($event->eventtype
== LESSON_EVENT_TYPE_OPEN
) {
1706 // If the event is for the lesson activity opening then we should
1707 // set the start time of the lesson activity to be the new start
1708 // time of the event.
1709 if ($lesson->available
!= $event->timestart
) {
1710 $lesson->available
= $event->timestart
;
1711 $lesson->timemodified
= time();
1714 } else if ($event->eventtype
== LESSON_EVENT_TYPE_CLOSE
) {
1715 // If the event is for the lesson activity closing then we should
1716 // set the end time of the lesson activity to be the new start
1717 // time of the event.
1718 if ($lesson->deadline
!= $event->timestart
) {
1719 $lesson->deadline
= $event->timestart
;
1725 $lesson->timemodified
= time();
1726 $DB->update_record('lesson', $lesson);
1727 $event = \core\event\course_module_updated
::create_from_cm($coursemodule, $context);
1733 * Callback to fetch the activity event type lang string.
1735 * @param string $eventtype The event type.
1736 * @return lang_string The event type lang string.
1738 function mod_lesson_core_calendar_get_event_action_string(string $eventtype): string {
1739 $modulename = get_string('modulename', 'lesson');
1741 switch ($eventtype) {
1742 case LESSON_EVENT_TYPE_OPEN
:
1743 $identifier = 'lessoneventopens';
1745 case LESSON_EVENT_TYPE_CLOSE
:
1746 $identifier = 'lessoneventcloses';
1749 return get_string('requiresaction', 'calendar', $modulename);
1752 return get_string($identifier, 'lesson', $modulename);