weekly release 3.2.1+
[moodle.git] / mod / lesson / lib.php
blobc0bf7e0ddb7c623e76e30a799cf0251f815d8f84
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Standard library of functions and constants for lesson
21 * @package mod_lesson
22 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 **/
26 defined('MOODLE_INTERNAL') || die();
28 /* Do not include any libraries here! */
30 /**
31 * Given an object containing all the necessary data,
32 * (defined by the form in mod_form.php) this function
33 * will create a new instance and return the id number
34 * of the new instance.
36 * @global object
37 * @global object
38 * @param object $lesson Lesson post data from the form
39 * @return int
40 **/
41 function lesson_add_instance($data, $mform) {
42 global $DB;
44 $cmid = $data->coursemodule;
45 $draftitemid = $data->mediafile;
46 $context = context_module::instance($cmid);
48 lesson_process_pre_save($data);
50 unset($data->mediafile);
51 $lessonid = $DB->insert_record("lesson", $data);
52 $data->id = $lessonid;
54 lesson_update_media_file($lessonid, $context, $draftitemid);
56 lesson_process_post_save($data);
58 lesson_grade_item_update($data);
60 return $lessonid;
63 /**
64 * Given an object containing all the necessary data,
65 * (defined by the form in mod_form.php) this function
66 * will update an existing instance with new data.
68 * @global object
69 * @param object $lesson Lesson post data from the form
70 * @return boolean
71 **/
72 function lesson_update_instance($data, $mform) {
73 global $DB;
75 $data->id = $data->instance;
76 $cmid = $data->coursemodule;
77 $draftitemid = $data->mediafile;
78 $context = context_module::instance($cmid);
80 lesson_process_pre_save($data);
82 unset($data->mediafile);
83 $DB->update_record("lesson", $data);
85 lesson_update_media_file($data->id, $context, $draftitemid);
87 lesson_process_post_save($data);
89 // update grade item definition
90 lesson_grade_item_update($data);
92 // update grades - TODO: do it only when grading style changes
93 lesson_update_grades($data, 0, false);
95 return true;
98 /**
99 * This function updates the events associated to the lesson.
100 * If $override is non-zero, then it updates only the events
101 * associated with the specified override.
103 * @uses LESSON_MAX_EVENT_LENGTH
104 * @param object $lesson the lesson object.
105 * @param object $override (optional) limit to a specific override
107 function lesson_update_events($lesson, $override = null) {
108 global $CFG, $DB;
110 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
111 require_once($CFG->dirroot . '/calendar/lib.php');
113 // Load the old events relating to this lesson.
114 $conds = array('modulename' => 'lesson',
115 'instance' => $lesson->id);
116 if (!empty($override)) {
117 // Only load events for this override.
118 if (isset($override->userid)) {
119 $conds['userid'] = $override->userid;
120 } else {
121 $conds['groupid'] = $override->groupid;
124 $oldevents = $DB->get_records('event', $conds);
126 // Now make a todo list of all that needs to be updated.
127 if (empty($override)) {
128 // We are updating the primary settings for the lesson, so we
129 // need to add all the overrides.
130 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $lesson->id));
131 // As well as the original lesson (empty override).
132 $overrides[] = new stdClass();
133 } else {
134 // Just do the one override.
135 $overrides = array($override);
138 foreach ($overrides as $current) {
139 $groupid = isset($current->groupid) ? $current->groupid : 0;
140 $userid = isset($current->userid) ? $current->userid : 0;
141 $available = isset($current->available) ? $current->available : $lesson->available;
142 $deadline = isset($current->deadline) ? $current->deadline : $lesson->deadline;
144 // Only add open/close events for an override if they differ from the lesson default.
145 $addopen = empty($current->id) || !empty($current->available);
146 $addclose = empty($current->id) || !empty($current->deadline);
148 if (!empty($lesson->coursemodule)) {
149 $cmid = $lesson->coursemodule;
150 } else {
151 $cmid = get_coursemodule_from_instance('lesson', $lesson->id, $lesson->course)->id;
154 $event = new stdClass();
155 $event->description = format_module_intro('lesson', $lesson, $cmid);
156 // Events module won't show user events when the courseid is nonzero.
157 $event->courseid = ($userid) ? 0 : $lesson->course;
158 $event->groupid = $groupid;
159 $event->userid = $userid;
160 $event->modulename = 'lesson';
161 $event->instance = $lesson->id;
162 $event->timestart = $available;
163 $event->timeduration = max($deadline - $available, 0);
164 $event->visible = instance_is_visible('lesson', $lesson);
165 $event->eventtype = 'open';
167 // Determine the event name.
168 if ($groupid) {
169 $params = new stdClass();
170 $params->lesson = $lesson->name;
171 $params->group = groups_get_group_name($groupid);
172 if ($params->group === false) {
173 // Group doesn't exist, just skip it.
174 continue;
176 $eventname = get_string('overridegroupeventname', 'lesson', $params);
177 } else if ($userid) {
178 $params = new stdClass();
179 $params->lesson = $lesson->name;
180 $eventname = get_string('overrideusereventname', 'lesson', $params);
181 } else {
182 $eventname = $lesson->name;
184 if ($addopen or $addclose) {
185 if ($deadline and $available and $event->timeduration <= LESSON_MAX_EVENT_LENGTH) {
186 // Single event for the whole lesson.
187 if ($oldevent = array_shift($oldevents)) {
188 $event->id = $oldevent->id;
189 } else {
190 unset($event->id);
192 $event->name = $eventname;
193 // The method calendar_event::create will reuse a db record if the id field is set.
194 calendar_event::create($event);
195 } else {
196 // Separate start and end events.
197 $event->timeduration = 0;
198 if ($available && $addopen) {
199 if ($oldevent = array_shift($oldevents)) {
200 $event->id = $oldevent->id;
201 } else {
202 unset($event->id);
204 $event->name = $eventname.' ('.get_string('lessonopens', 'lesson').')';
205 // The method calendar_event::create will reuse a db record if the id field is set.
206 calendar_event::create($event);
208 if ($deadline && $addclose) {
209 if ($oldevent = array_shift($oldevents)) {
210 $event->id = $oldevent->id;
211 } else {
212 unset($event->id);
214 $event->name = $eventname.' ('.get_string('lessoncloses', 'lesson').')';
215 $event->timestart = $deadline;
216 $event->eventtype = 'close';
217 calendar_event::create($event);
223 // Delete any leftover events.
224 foreach ($oldevents as $badevent) {
225 $badevent = calendar_event::load($badevent);
226 $badevent->delete();
231 * This standard function will check all instances of this module
232 * and make sure there are up-to-date events created for each of them.
233 * If courseid = 0, then every lesson event in the site is checked, else
234 * only lesson events belonging to the course specified are checked.
235 * This function is used, in its new format, by restore_refresh_events()
237 * @param int $courseid
238 * @return bool
240 function lesson_refresh_events($courseid = 0) {
241 global $DB;
243 if ($courseid == 0) {
244 if (!$lessons = $DB->get_records('lesson')) {
245 return true;
247 } else {
248 if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) {
249 return true;
253 foreach ($lessons as $lesson) {
254 lesson_update_events($lesson);
257 return true;
261 * Given an ID of an instance of this module,
262 * this function will permanently delete the instance
263 * and any data that depends on it.
265 * @global object
266 * @param int $id
267 * @return bool
269 function lesson_delete_instance($id) {
270 global $DB, $CFG;
271 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
273 $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST);
274 $lesson = new lesson($lesson);
275 return $lesson->delete();
279 * Return a small object with summary information about what a
280 * user has done with a given particular instance of this module
281 * Used for user activity reports.
282 * $return->time = the time they did it
283 * $return->info = a short text description
285 * @global object
286 * @param object $course
287 * @param object $user
288 * @param object $mod
289 * @param object $lesson
290 * @return object
292 function lesson_user_outline($course, $user, $mod, $lesson) {
293 global $CFG, $DB;
295 require_once("$CFG->libdir/gradelib.php");
296 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
297 $return = new stdClass();
299 if (empty($grades->items[0]->grades)) {
300 $return->info = get_string("nolessonattempts", "lesson");
301 } else {
302 $grade = reset($grades->items[0]->grades);
303 if (empty($grade->grade)) {
305 // Check to see if it an ungraded / incomplete attempt.
306 $sql = "SELECT *
307 FROM {lesson_timer}
308 WHERE lessonid = :lessonid
309 AND userid = :userid
310 ORDER BY starttime DESC";
311 $params = array('lessonid' => $lesson->id, 'userid' => $user->id);
313 if ($attempts = $DB->get_records_sql($sql, $params, 0, 1)) {
314 $attempt = reset($attempts);
315 if ($attempt->completed) {
316 $return->info = get_string("completed", "lesson");
317 } else {
318 $return->info = get_string("notyetcompleted", "lesson");
320 $return->time = $attempt->lessontime;
321 } else {
322 $return->info = get_string("nolessonattempts", "lesson");
324 } else {
325 $return->info = get_string("grade") . ': ' . $grade->str_long_grade;
327 // Datesubmitted == time created. dategraded == time modified or time overridden.
328 // If grade was last modified by the user themselves use date graded. Otherwise use date submitted.
329 // TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704.
330 if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
331 $return->time = $grade->dategraded;
332 } else {
333 $return->time = $grade->datesubmitted;
337 return $return;
341 * Print a detailed representation of what a user has done with
342 * a given particular instance of this module, for user activity reports.
344 * @global object
345 * @param object $course
346 * @param object $user
347 * @param object $mod
348 * @param object $lesson
349 * @return bool
351 function lesson_user_complete($course, $user, $mod, $lesson) {
352 global $DB, $OUTPUT, $CFG;
354 require_once("$CFG->libdir/gradelib.php");
356 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
358 // Display the grade and feedback.
359 if (empty($grades->items[0]->grades)) {
360 echo $OUTPUT->container(get_string("nolessonattempts", "lesson"));
361 } else {
362 $grade = reset($grades->items[0]->grades);
363 if (empty($grade->grade)) {
364 // Check to see if it an ungraded / incomplete attempt.
365 $sql = "SELECT *
366 FROM {lesson_timer}
367 WHERE lessonid = :lessonid
368 AND userid = :userid
369 ORDER by starttime desc";
370 $params = array('lessonid' => $lesson->id, 'userid' => $user->id);
372 if ($attempt = $DB->get_record_sql($sql, $params, IGNORE_MULTIPLE)) {
373 if ($attempt->completed) {
374 $status = get_string("completed", "lesson");
375 } else {
376 $status = get_string("notyetcompleted", "lesson");
378 } else {
379 $status = get_string("nolessonattempts", "lesson");
381 } else {
382 $status = get_string("grade") . ': ' . $grade->str_long_grade;
385 // Display the grade or lesson status if there isn't one.
386 echo $OUTPUT->container($status);
388 if ($grade->str_feedback) {
389 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
393 // Display the lesson progress.
394 // Attempt, pages viewed, questions answered, correct answers, time.
395 $params = array ("lessonid" => $lesson->id, "userid" => $user->id);
396 $attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
397 $branches = $DB->get_records_select("lesson_branch", "lessonid = :lessonid AND userid = :userid", $params, "retry, timeseen");
398 if (!empty($attempts) or !empty($branches)) {
399 echo $OUTPUT->box_start();
400 $table = new html_table();
401 // Table Headings.
402 $table->head = array (get_string("attemptheader", "lesson"),
403 get_string("totalpagesviewedheader", "lesson"),
404 get_string("numberofpagesviewedheader", "lesson"),
405 get_string("numberofcorrectanswersheader", "lesson"),
406 get_string("time"));
407 $table->width = "100%";
408 $table->align = array ("center", "center", "center", "center", "center");
409 $table->size = array ("*", "*", "*", "*", "*");
410 $table->cellpadding = 2;
411 $table->cellspacing = 0;
413 $retry = 0;
414 $nquestions = 0;
415 $npages = 0;
416 $ncorrect = 0;
418 // Filter question pages (from lesson_attempts).
419 foreach ($attempts as $attempt) {
420 if ($attempt->retry == $retry) {
421 $npages++;
422 $nquestions++;
423 if ($attempt->correct) {
424 $ncorrect++;
426 $timeseen = $attempt->timeseen;
427 } else {
428 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
429 $retry++;
430 $nquestions = 1;
431 $npages = 1;
432 if ($attempt->correct) {
433 $ncorrect = 1;
434 } else {
435 $ncorrect = 0;
440 // Filter content pages (from lesson_branch).
441 foreach ($branches as $branch) {
442 if ($branch->retry == $retry) {
443 $npages++;
445 $timeseen = $branch->timeseen;
446 } else {
447 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
448 $retry++;
449 $npages = 1;
452 if ($npages > 0) {
453 $table->data[] = array($retry + 1, $npages, $nquestions, $ncorrect, userdate($timeseen));
455 echo html_writer::table($table);
456 echo $OUTPUT->box_end();
459 return true;
463 * Prints lesson summaries on MyMoodle Page
465 * Prints lesson name, due date and attempt information on
466 * lessons that have a deadline that has not already passed
467 * and it is available for taking.
469 * @global object
470 * @global stdClass
471 * @global object
472 * @uses CONTEXT_MODULE
473 * @param array $courses An array of course objects to get lesson instances from
474 * @param array $htmlarray Store overview output array( course ID => 'lesson' => HTML output )
475 * @return void
477 function lesson_print_overview($courses, &$htmlarray) {
478 global $USER, $CFG, $DB, $OUTPUT;
480 if (!$lessons = get_all_instances_in_courses('lesson', $courses)) {
481 return;
484 // Get all of the current users attempts on all lessons.
485 $params = array($USER->id);
486 $sql = 'SELECT lessonid, userid, count(userid) as attempts
487 FROM {lesson_grades}
488 WHERE userid = ?
489 GROUP BY lessonid, userid';
490 $allattempts = $DB->get_records_sql($sql, $params);
491 $completedattempts = array();
492 foreach ($allattempts as $myattempt) {
493 $completedattempts[$myattempt->lessonid] = $myattempt->attempts;
496 // Get the current course ID.
497 $listoflessons = array();
498 foreach ($lessons as $lesson) {
499 $listoflessons[] = $lesson->id;
501 // Get the last page viewed by the current user for every lesson in this course.
502 list($insql, $inparams) = $DB->get_in_or_equal($listoflessons, SQL_PARAMS_NAMED);
503 $dbparams = array_merge($inparams, array('userid' => $USER->id));
505 // Get the lesson attempts for the user that have the maximum 'timeseen' value.
506 $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.answerid as nextpageid, p.qtype ";
507 $from = "FROM {lesson_attempts} l
508 JOIN (
509 SELECT idselect.lessonid, idselect.userid, MAX(idselect.id) AS id
510 FROM {lesson_attempts} idselect
511 JOIN (
512 SELECT lessonid, userid, MAX(timeseen) AS timeseen
513 FROM {lesson_attempts}
514 WHERE userid = :userid
515 AND lessonid $insql
516 GROUP BY userid, lessonid
517 ) timeselect
518 ON timeselect.timeseen = idselect.timeseen
519 AND timeselect.userid = idselect.userid
520 AND timeselect.lessonid = idselect.lessonid
521 GROUP BY idselect.userid, idselect.lessonid
522 ) aid
523 ON l.id = aid.id
524 JOIN {lesson_pages} p
525 ON l.pageid = p.id ";
526 $lastattempts = $DB->get_records_sql($select . $from, $dbparams);
528 // Now, get the lesson branches for the user that have the maximum 'timeseen' value.
529 $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.nextpageid, p.qtype ";
530 $from = str_replace('{lesson_attempts}', '{lesson_branch}', $from);
531 $lastbranches = $DB->get_records_sql($select . $from, $dbparams);
533 $lastviewed = array();
534 foreach ($lastattempts as $lastattempt) {
535 $lastviewed[$lastattempt->lessonid] = $lastattempt;
538 // Go through the branch times and record the 'timeseen' value if it doesn't exist
539 // for the lesson, or replace it if it exceeds the current recorded time.
540 foreach ($lastbranches as $lastbranch) {
541 if (!isset($lastviewed[$lastbranch->lessonid])) {
542 $lastviewed[$lastbranch->lessonid] = $lastbranch;
543 } else if ($lastviewed[$lastbranch->lessonid]->timeseen < $lastbranch->timeseen) {
544 $lastviewed[$lastbranch->lessonid] = $lastbranch;
548 // Since we have lessons in this course, now include the constants we need.
549 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
551 $now = time();
552 foreach ($lessons as $lesson) {
553 if ($lesson->deadline != 0 // The lesson has a deadline
554 and $lesson->deadline >= $now // And it is before the deadline has been met
555 and ($lesson->available == 0 or $lesson->available <= $now)) { // And the lesson is available
557 // Visibility.
558 $class = (!$lesson->visible) ? 'dimmed' : '';
560 // Context.
561 $context = context_module::instance($lesson->coursemodule);
563 // Link to activity.
564 $url = new moodle_url('/mod/lesson/view.php', array('id' => $lesson->coursemodule));
565 $url = html_writer::link($url, format_string($lesson->name, true, array('context' => $context)), array('class' => $class));
566 $str = $OUTPUT->box(get_string('lessonname', 'lesson', $url), 'name');
568 // Deadline.
569 $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info');
571 // Attempt information.
572 if (has_capability('mod/lesson:manage', $context)) {
573 // This is a teacher, Get the Number of user attempts.
574 $attempts = $DB->count_records('lesson_grades', array('lessonid' => $lesson->id));
575 $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info');
576 $str = $OUTPUT->box($str, 'lesson overview');
577 } else {
578 // This is a student, See if the user has at least started the lesson.
579 if (isset($lastviewed[$lesson->id]->timeseen)) {
580 // See if the user has finished this attempt.
581 if (isset($completedattempts[$lesson->id]) &&
582 ($completedattempts[$lesson->id] == ($lastviewed[$lesson->id]->retry + 1))) {
583 // Are additional attempts allowed?
584 if ($lesson->retake) {
585 // User can retake the lesson.
586 $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info');
587 $str = $OUTPUT->box($str, 'lesson overview');
588 } else {
589 // User has completed the lesson and no retakes are allowed.
590 $str = '';
593 } else {
594 // The last attempt was not finished or the lesson does not contain questions.
595 // See if the last page viewed was a branchtable.
596 require_once($CFG->dirroot . '/mod/lesson/pagetypes/branchtable.php');
597 if ($lastviewed[$lesson->id]->qtype == LESSON_PAGE_BRANCHTABLE) {
598 // See if the next pageid is the end of lesson.
599 if ($lastviewed[$lesson->id]->nextpageid == LESSON_EOL) {
600 // The last page viewed was the End of Lesson.
601 if ($lesson->retake) {
602 // User can retake the lesson.
603 $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info');
604 $str = $OUTPUT->box($str, 'lesson overview');
605 } else {
606 // User has completed the lesson and no retakes are allowed.
607 $str = '';
610 } else {
611 // The last page viewed was NOT the end of lesson.
612 $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info');
613 $str = $OUTPUT->box($str, 'lesson overview');
616 } else {
617 // Last page was a question page, so the attempt is not completed yet.
618 $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info');
619 $str = $OUTPUT->box($str, 'lesson overview');
623 } else {
624 // User has not yet started this lesson.
625 $str .= $OUTPUT->box(get_string('nolessonattempts', 'lesson'), 'info');
626 $str = $OUTPUT->box($str, 'lesson overview');
629 if (!empty($str)) {
630 if (empty($htmlarray[$lesson->course]['lesson'])) {
631 $htmlarray[$lesson->course]['lesson'] = $str;
632 } else {
633 $htmlarray[$lesson->course]['lesson'] .= $str;
641 * Function to be run periodically according to the moodle cron
642 * This function searches for things that need to be done, such
643 * as sending out mail, toggling flags etc ...
644 * @global stdClass
645 * @return bool true
647 function lesson_cron () {
648 global $CFG;
650 return true;
654 * Return grade for given user or all users.
656 * @global stdClass
657 * @global object
658 * @param int $lessonid id of lesson
659 * @param int $userid optional user id, 0 means all users
660 * @return array array of grades, false if none
662 function lesson_get_user_grades($lesson, $userid=0) {
663 global $CFG, $DB;
665 $params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id);
667 if (!empty($userid)) {
668 $params["userid"] = $userid;
669 $params["userid2"] = $userid;
670 $user = "AND u.id = :userid";
671 $fuser = "AND uu.id = :userid2";
673 else {
674 $user="";
675 $fuser="";
678 if ($lesson->retake) {
679 if ($lesson->usemaxgrade) {
680 $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade
681 FROM {user} u, {lesson_grades} g
682 WHERE u.id = g.userid AND g.lessonid = :lessonid
683 $user
684 GROUP BY u.id";
685 } else {
686 $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade
687 FROM {user} u, {lesson_grades} g
688 WHERE u.id = g.userid AND g.lessonid = :lessonid
689 $user
690 GROUP BY u.id";
692 unset($params['lessonid2']);
693 unset($params['userid2']);
694 } else {
695 // use only first attempts (with lowest id in lesson_grades table)
696 $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted
697 FROM {user} uu, {lesson_grades} gg
698 WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2
699 $fuser
700 GROUP BY uu.id";
702 $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade
703 FROM {user} u, {lesson_grades} g, ($firstonly) f
704 WHERE u.id = g.userid AND g.lessonid = :lessonid
705 AND g.id = f.firstcompleted AND g.userid=f.userid
706 $user";
709 return $DB->get_records_sql($sql, $params);
713 * Update grades in central gradebook
715 * @category grade
716 * @param object $lesson
717 * @param int $userid specific user only, 0 means all
718 * @param bool $nullifnone
720 function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
721 global $CFG, $DB;
722 require_once($CFG->libdir.'/gradelib.php');
724 if ($lesson->grade == 0 || $lesson->practice) {
725 lesson_grade_item_update($lesson);
727 } else if ($grades = lesson_get_user_grades($lesson, $userid)) {
728 lesson_grade_item_update($lesson, $grades);
730 } else if ($userid and $nullifnone) {
731 $grade = new stdClass();
732 $grade->userid = $userid;
733 $grade->rawgrade = null;
734 lesson_grade_item_update($lesson, $grade);
736 } else {
737 lesson_grade_item_update($lesson);
742 * Create grade item for given lesson
744 * @category grade
745 * @uses GRADE_TYPE_VALUE
746 * @uses GRADE_TYPE_NONE
747 * @param object $lesson object with extra cmidnumber
748 * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
749 * @return int 0 if ok, error code otherwise
751 function lesson_grade_item_update($lesson, $grades=null) {
752 global $CFG;
753 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
754 require_once($CFG->libdir.'/gradelib.php');
757 if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present
758 $params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber);
759 } else {
760 $params = array('itemname'=>$lesson->name);
763 if (!$lesson->practice and $lesson->grade > 0) {
764 $params['gradetype'] = GRADE_TYPE_VALUE;
765 $params['grademax'] = $lesson->grade;
766 $params['grademin'] = 0;
767 } else if (!$lesson->practice and $lesson->grade < 0) {
768 $params['gradetype'] = GRADE_TYPE_SCALE;
769 $params['scaleid'] = -$lesson->grade;
771 // Make sure current grade fetched correctly from $grades
772 $currentgrade = null;
773 if (!empty($grades)) {
774 if (is_array($grades)) {
775 $currentgrade = reset($grades);
776 } else {
777 $currentgrade = $grades;
781 // When converting a score to a scale, use scale's grade maximum to calculate it.
782 if (!empty($currentgrade) && $currentgrade->rawgrade !== null) {
783 $grade = grade_get_grades($lesson->course, 'mod', 'lesson', $lesson->id, $currentgrade->userid);
784 $params['grademax'] = reset($grade->items)->grademax;
786 } else {
787 $params['gradetype'] = GRADE_TYPE_NONE;
790 if ($grades === 'reset') {
791 $params['reset'] = true;
792 $grades = null;
793 } else if (!empty($grades)) {
794 // Need to calculate raw grade (Note: $grades has many forms)
795 if (is_object($grades)) {
796 $grades = array($grades->userid => $grades);
797 } else if (array_key_exists('userid', $grades)) {
798 $grades = array($grades['userid'] => $grades);
800 foreach ($grades as $key => $grade) {
801 if (!is_array($grade)) {
802 $grades[$key] = $grade = (array) $grade;
804 //check raw grade isnt null otherwise we erroneously insert a grade of 0
805 if ($grade['rawgrade'] !== null) {
806 $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100);
807 } else {
808 //setting rawgrade to null just in case user is deleting a grade
809 $grades[$key]['rawgrade'] = null;
814 return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params);
818 * List the actions that correspond to a view of this module.
819 * This is used by the participation report.
821 * Note: This is not used by new logging system. Event with
822 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
823 * be considered as view action.
825 * @return array
827 function lesson_get_view_actions() {
828 return array('view','view all');
832 * List the actions that correspond to a post of this module.
833 * This is used by the participation report.
835 * Note: This is not used by new logging system. Event with
836 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
837 * will be considered as post action.
839 * @return array
841 function lesson_get_post_actions() {
842 return array('end','start');
846 * Runs any processes that must run before
847 * a lesson insert/update
849 * @global object
850 * @param object $lesson Lesson form data
851 * @return void
853 function lesson_process_pre_save(&$lesson) {
854 global $DB;
856 $lesson->timemodified = time();
858 if (empty($lesson->timelimit)) {
859 $lesson->timelimit = 0;
861 if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) {
862 $lesson->timespent = 0;
864 if (!isset($lesson->completed)) {
865 $lesson->completed = 0;
867 if (empty($lesson->gradebetterthan) or !is_numeric($lesson->gradebetterthan) or $lesson->gradebetterthan < 0) {
868 $lesson->gradebetterthan = 0;
869 } else if ($lesson->gradebetterthan > 100) {
870 $lesson->gradebetterthan = 100;
873 if (empty($lesson->width)) {
874 $lesson->width = 640;
876 if (empty($lesson->height)) {
877 $lesson->height = 480;
879 if (empty($lesson->bgcolor)) {
880 $lesson->bgcolor = '#FFFFFF';
883 // Conditions for dependency
884 $conditions = new stdClass;
885 $conditions->timespent = $lesson->timespent;
886 $conditions->completed = $lesson->completed;
887 $conditions->gradebetterthan = $lesson->gradebetterthan;
888 $lesson->conditions = serialize($conditions);
889 unset($lesson->timespent);
890 unset($lesson->completed);
891 unset($lesson->gradebetterthan);
893 if (empty($lesson->password)) {
894 unset($lesson->password);
899 * Runs any processes that must be run
900 * after a lesson insert/update
902 * @global object
903 * @param object $lesson Lesson form data
904 * @return void
906 function lesson_process_post_save(&$lesson) {
907 // Update the events relating to this lesson.
908 lesson_update_events($lesson);
913 * Implementation of the function for printing the form elements that control
914 * whether the course reset functionality affects the lesson.
916 * @param $mform form passed by reference
918 function lesson_reset_course_form_definition(&$mform) {
919 $mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson'));
920 $mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts','lesson'));
921 $mform->addElement('advcheckbox', 'reset_lesson_user_overrides',
922 get_string('removealluseroverrides', 'lesson'));
923 $mform->addElement('advcheckbox', 'reset_lesson_group_overrides',
924 get_string('removeallgroupoverrides', 'lesson'));
928 * Course reset form defaults.
929 * @param object $course
930 * @return array
932 function lesson_reset_course_form_defaults($course) {
933 return array('reset_lesson' => 1,
934 'reset_lesson_group_overrides' => 1,
935 'reset_lesson_user_overrides' => 1);
939 * Removes all grades from gradebook
941 * @global stdClass
942 * @global object
943 * @param int $courseid
944 * @param string optional type
946 function lesson_reset_gradebook($courseid, $type='') {
947 global $CFG, $DB;
949 $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
950 FROM {lesson} l, {course_modules} cm, {modules} m
951 WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course";
952 $params = array ("course" => $courseid);
953 if ($lessons = $DB->get_records_sql($sql,$params)) {
954 foreach ($lessons as $lesson) {
955 lesson_grade_item_update($lesson, 'reset');
961 * Actual implementation of the reset course functionality, delete all the
962 * lesson attempts for course $data->courseid.
964 * @global stdClass
965 * @global object
966 * @param object $data the data submitted from the reset course.
967 * @return array status array
969 function lesson_reset_userdata($data) {
970 global $CFG, $DB;
972 $componentstr = get_string('modulenameplural', 'lesson');
973 $status = array();
975 if (!empty($data->reset_lesson)) {
976 $lessonssql = "SELECT l.id
977 FROM {lesson} l
978 WHERE l.course=:course";
980 $params = array ("course" => $data->courseid);
981 $lessons = $DB->get_records_sql($lessonssql, $params);
983 // Get rid of attempts files.
984 $fs = get_file_storage();
985 if ($lessons) {
986 foreach ($lessons as $lessonid => $unused) {
987 if (!$cm = get_coursemodule_from_instance('lesson', $lessonid)) {
988 continue;
990 $context = context_module::instance($cm->id);
991 $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses');
995 $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params);
996 $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params);
997 $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params);
998 $DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params);
1000 // remove all grades from gradebook
1001 if (empty($data->reset_gradebook_grades)) {
1002 lesson_reset_gradebook($data->courseid);
1005 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false);
1008 // Remove user overrides.
1009 if (!empty($data->reset_lesson_user_overrides)) {
1010 $DB->delete_records_select('lesson_overrides',
1011 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid));
1012 $status[] = array(
1013 'component' => $componentstr,
1014 'item' => get_string('useroverridesdeleted', 'lesson'),
1015 'error' => false);
1017 // Remove group overrides.
1018 if (!empty($data->reset_lesson_group_overrides)) {
1019 $DB->delete_records_select('lesson_overrides',
1020 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid));
1021 $status[] = array(
1022 'component' => $componentstr,
1023 'item' => get_string('groupoverridesdeleted', 'lesson'),
1024 'error' => false);
1026 /// updating dates - shift may be negative too
1027 if ($data->timeshift) {
1028 $DB->execute("UPDATE {lesson_overrides}
1029 SET available = available + ?
1030 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
1031 AND available <> 0", array($data->timeshift, $data->courseid));
1032 $DB->execute("UPDATE {lesson_overrides}
1033 SET deadline = deadline + ?
1034 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
1035 AND deadline <> 0", array($data->timeshift, $data->courseid));
1037 shift_course_mod_dates('lesson', array('available', 'deadline'), $data->timeshift, $data->courseid);
1038 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
1041 return $status;
1045 * Returns all other caps used in module
1046 * @return array
1048 function lesson_get_extra_capabilities() {
1049 return array('moodle/site:accessallgroups');
1053 * @uses FEATURE_GROUPS
1054 * @uses FEATURE_GROUPINGS
1055 * @uses FEATURE_MOD_INTRO
1056 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
1057 * @uses FEATURE_GRADE_HAS_GRADE
1058 * @uses FEATURE_GRADE_OUTCOMES
1059 * @param string $feature FEATURE_xx constant for requested feature
1060 * @return mixed True if module supports feature, false if not, null if doesn't know
1062 function lesson_supports($feature) {
1063 switch($feature) {
1064 case FEATURE_GROUPS:
1065 return true;
1066 case FEATURE_GROUPINGS:
1067 return true;
1068 case FEATURE_MOD_INTRO:
1069 return true;
1070 case FEATURE_COMPLETION_TRACKS_VIEWS:
1071 return true;
1072 case FEATURE_GRADE_HAS_GRADE:
1073 return true;
1074 case FEATURE_COMPLETION_HAS_RULES:
1075 return true;
1076 case FEATURE_GRADE_OUTCOMES:
1077 return true;
1078 case FEATURE_BACKUP_MOODLE2:
1079 return true;
1080 case FEATURE_SHOW_DESCRIPTION:
1081 return true;
1082 default:
1083 return null;
1088 * Obtains the automatic completion state for this lesson based on any conditions
1089 * in lesson settings.
1091 * @param object $course Course
1092 * @param object $cm course-module
1093 * @param int $userid User ID
1094 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1095 * @return bool True if completed, false if not, $type if conditions not set.
1097 function lesson_get_completion_state($course, $cm, $userid, $type) {
1098 global $CFG, $DB;
1100 // Get lesson details.
1101 $lesson = $DB->get_record('lesson', array('id' => $cm->instance), '*',
1102 MUST_EXIST);
1104 $result = $type; // Default return value.
1105 // If completion option is enabled, evaluate it and return true/false.
1106 if ($lesson->completionendreached) {
1107 $value = $DB->record_exists('lesson_timer', array(
1108 'lessonid' => $lesson->id, 'userid' => $userid, 'completed' => 1));
1109 if ($type == COMPLETION_AND) {
1110 $result = $result && $value;
1111 } else {
1112 $result = $result || $value;
1115 if ($lesson->completiontimespent != 0) {
1116 $duration = $DB->get_field_sql(
1117 "SELECT SUM(lessontime - starttime)
1118 FROM {lesson_timer}
1119 WHERE lessonid = :lessonid
1120 AND userid = :userid",
1121 array('userid' => $userid, 'lessonid' => $lesson->id));
1122 if (!$duration) {
1123 $duration = 0;
1125 if ($type == COMPLETION_AND) {
1126 $result = $result && ($lesson->completiontimespent < $duration);
1127 } else {
1128 $result = $result || ($lesson->completiontimespent < $duration);
1131 return $result;
1134 * This function extends the settings navigation block for the site.
1136 * It is safe to rely on PAGE here as we will only ever be within the module
1137 * context when this is called
1139 * @param settings_navigation $settings
1140 * @param navigation_node $lessonnode
1142 function lesson_extend_settings_navigation($settings, $lessonnode) {
1143 global $PAGE, $DB;
1145 // We want to add these new nodes after the Edit settings node, and before the
1146 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1147 $keys = $lessonnode->get_children_key_list();
1148 $beforekey = null;
1149 $i = array_search('modedit', $keys);
1150 if ($i === false and array_key_exists(0, $keys)) {
1151 $beforekey = $keys[0];
1152 } else if (array_key_exists($i + 1, $keys)) {
1153 $beforekey = $keys[$i + 1];
1156 if (has_capability('mod/lesson:manageoverrides', $PAGE->cm->context)) {
1157 $url = new moodle_url('/mod/lesson/overrides.php', array('cmid' => $PAGE->cm->id));
1158 $node = navigation_node::create(get_string('groupoverrides', 'lesson'),
1159 new moodle_url($url, array('mode' => 'group')),
1160 navigation_node::TYPE_SETTING, null, 'mod_lesson_groupoverrides');
1161 $lessonnode->add_node($node, $beforekey);
1163 $node = navigation_node::create(get_string('useroverrides', 'lesson'),
1164 new moodle_url($url, array('mode' => 'user')),
1165 navigation_node::TYPE_SETTING, null, 'mod_lesson_useroverrides');
1166 $lessonnode->add_node($node, $beforekey);
1169 if (has_capability('mod/lesson:edit', $PAGE->cm->context)) {
1170 $url = new moodle_url('/mod/lesson/view.php', array('id' => $PAGE->cm->id));
1171 $lessonnode->add(get_string('preview', 'lesson'), $url);
1172 $editnode = $lessonnode->add(get_string('edit', 'lesson'));
1173 $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'collapsed'));
1174 $editnode->add(get_string('collapsed', 'lesson'), $url);
1175 $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm->id, 'mode' => 'full'));
1176 $editnode->add(get_string('full', 'lesson'), $url);
1179 if (has_capability('mod/lesson:viewreports', $PAGE->cm->context)) {
1180 $reportsnode = $lessonnode->add(get_string('reports', 'lesson'));
1181 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportoverview'));
1182 $reportsnode->add(get_string('overview', 'lesson'), $url);
1183 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportdetail'));
1184 $reportsnode->add(get_string('detailedstats', 'lesson'), $url);
1187 if (has_capability('mod/lesson:grade', $PAGE->cm->context)) {
1188 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm->id));
1189 $lessonnode->add(get_string('manualgrading', 'lesson'), $url);
1195 * Get list of available import or export formats
1197 * Copied and modified from lib/questionlib.php
1199 * @param string $type 'import' if import list, otherwise export list assumed
1200 * @return array sorted list of import/export formats available
1202 function lesson_get_import_export_formats($type) {
1203 global $CFG;
1204 $fileformats = core_component::get_plugin_list("qformat");
1206 $fileformatname=array();
1207 foreach ($fileformats as $fileformat=>$fdir) {
1208 $format_file = "$fdir/format.php";
1209 if (file_exists($format_file) ) {
1210 require_once($format_file);
1211 } else {
1212 continue;
1214 $classname = "qformat_$fileformat";
1215 $format_class = new $classname();
1216 if ($type=='import') {
1217 $provided = $format_class->provide_import();
1218 } else {
1219 $provided = $format_class->provide_export();
1221 if ($provided) {
1222 $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat);
1225 natcasesort($fileformatnames);
1227 return $fileformatnames;
1231 * Serves the lesson attachments. Implements needed access control ;-)
1233 * @package mod_lesson
1234 * @category files
1235 * @param stdClass $course course object
1236 * @param stdClass $cm course module object
1237 * @param stdClass $context context object
1238 * @param string $filearea file area
1239 * @param array $args extra arguments
1240 * @param bool $forcedownload whether or not force download
1241 * @param array $options additional options affecting the file serving
1242 * @return bool false if file not found, does not return if found - justsend the file
1244 function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1245 global $CFG, $DB;
1247 if ($context->contextlevel != CONTEXT_MODULE) {
1248 return false;
1251 $fileareas = lesson_get_file_areas();
1252 if (!array_key_exists($filearea, $fileareas)) {
1253 return false;
1256 if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance))) {
1257 return false;
1260 require_course_login($course, true, $cm);
1262 if ($filearea === 'page_contents') {
1263 $pageid = (int)array_shift($args);
1264 if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) {
1265 return false;
1267 $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args);
1269 } else if ($filearea === 'page_answers' || $filearea === 'page_responses') {
1270 $itemid = (int)array_shift($args);
1271 if (!$pageanswers = $DB->get_record('lesson_answers', array('id' => $itemid))) {
1272 return false;
1274 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1276 } else if ($filearea === 'essay_responses') {
1277 $itemid = (int)array_shift($args);
1278 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $itemid))) {
1279 return false;
1281 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1283 } else if ($filearea === 'mediafile') {
1284 if (count($args) > 1) {
1285 // Remove the itemid when it appears to be part of the arguments. If there is only one argument
1286 // then it is surely the file name. The itemid is sometimes used to prevent browser caching.
1287 array_shift($args);
1289 $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args);
1291 } else {
1292 return false;
1295 $fs = get_file_storage();
1296 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1297 return false;
1300 // finally send the file
1301 send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security!
1305 * Returns an array of file areas
1307 * @package mod_lesson
1308 * @category files
1309 * @return array a list of available file areas
1311 function lesson_get_file_areas() {
1312 $areas = array();
1313 $areas['page_contents'] = get_string('pagecontents', 'mod_lesson');
1314 $areas['mediafile'] = get_string('mediafile', 'mod_lesson');
1315 $areas['page_answers'] = get_string('pageanswers', 'mod_lesson');
1316 $areas['page_responses'] = get_string('pageresponses', 'mod_lesson');
1317 $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson');
1318 return $areas;
1322 * Returns a file_info_stored object for the file being requested here
1324 * @package mod_lesson
1325 * @category files
1326 * @global stdClass $CFG
1327 * @param file_browse $browser file browser instance
1328 * @param array $areas file areas
1329 * @param stdClass $course course object
1330 * @param stdClass $cm course module object
1331 * @param stdClass $context context object
1332 * @param string $filearea file area
1333 * @param int $itemid item ID
1334 * @param string $filepath file path
1335 * @param string $filename file name
1336 * @return file_info_stored
1338 function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
1339 global $CFG, $DB;
1341 if (!has_capability('moodle/course:managefiles', $context)) {
1342 // No peaking here for students!
1343 return null;
1346 // Mediafile area does not have sub directories, so let's select the default itemid to prevent
1347 // the user from selecting a directory to access the mediafile content.
1348 if ($filearea == 'mediafile' && is_null($itemid)) {
1349 $itemid = 0;
1352 if (is_null($itemid)) {
1353 return new mod_lesson_file_info($browser, $course, $cm, $context, $areas, $filearea);
1356 $fs = get_file_storage();
1357 $filepath = is_null($filepath) ? '/' : $filepath;
1358 $filename = is_null($filename) ? '.' : $filename;
1359 if (!$storedfile = $fs->get_file($context->id, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) {
1360 return null;
1363 $itemname = $filearea;
1364 if ($filearea == 'page_contents') {
1365 $itemname = $DB->get_field('lesson_pages', 'title', array('lessonid' => $cm->instance, 'id' => $itemid));
1366 $itemname = format_string($itemname, true, array('context' => $context));
1367 } else {
1368 $areas = lesson_get_file_areas();
1369 if (isset($areas[$filearea])) {
1370 $itemname = $areas[$filearea];
1374 $urlbase = $CFG->wwwroot . '/pluginfile.php';
1375 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false);
1380 * Return a list of page types
1381 * @param string $pagetype current page type
1382 * @param stdClass $parentcontext Block's parent context
1383 * @param stdClass $currentcontext Current context of block
1385 function lesson_page_type_list($pagetype, $parentcontext, $currentcontext) {
1386 $module_pagetype = array(
1387 'mod-lesson-*'=>get_string('page-mod-lesson-x', 'lesson'),
1388 'mod-lesson-view'=>get_string('page-mod-lesson-view', 'lesson'),
1389 'mod-lesson-edit'=>get_string('page-mod-lesson-edit', 'lesson'));
1390 return $module_pagetype;
1394 * Update the lesson activity to include any file
1395 * that was uploaded, or if there is none, set the
1396 * mediafile field to blank.
1398 * @param int $lessonid the lesson id
1399 * @param stdClass $context the context
1400 * @param int $draftitemid the draft item
1402 function lesson_update_media_file($lessonid, $context, $draftitemid) {
1403 global $DB;
1405 // Set the filestorage object.
1406 $fs = get_file_storage();
1407 // Save the file if it exists that is currently in the draft area.
1408 file_save_draft_area_files($draftitemid, $context->id, 'mod_lesson', 'mediafile', 0);
1409 // Get the file if it exists.
1410 $files = $fs->get_area_files($context->id, 'mod_lesson', 'mediafile', 0, 'itemid, filepath, filename', false);
1411 // Check that there is a file to process.
1412 if (count($files) == 1) {
1413 // Get the first (and only) file.
1414 $file = reset($files);
1415 // Set the mediafile column in the lessons table.
1416 $DB->set_field('lesson', 'mediafile', '/' . $file->get_filename(), array('id' => $lessonid));
1417 } else {
1418 // Set the mediafile column in the lessons table.
1419 $DB->set_field('lesson', 'mediafile', '', array('id' => $lessonid));