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();
28 /* Do not include any libraries here! */
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.
38 * @param object $lesson Lesson post data from the form
41 function lesson_add_instance($data, $mform) {
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);
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.
69 * @param object $lesson Lesson post data from the form
72 function lesson_update_instance($data, $mform) {
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);
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) {
110 require_once($CFG->dirroot
. '/calendar/lib.php');
112 // Load the old events relating to this lesson.
113 $conds = array('modulename' => 'lesson',
114 'instance' => $lesson->id
);
115 if (!empty($override)) {
116 // Only load events for this override.
117 if (isset($override->userid
)) {
118 $conds['userid'] = $override->userid
;
120 $conds['groupid'] = $override->groupid
;
123 $oldevents = $DB->get_records('event', $conds);
125 // Now make a todo list of all that needs to be updated.
126 if (empty($override)) {
127 // We are updating the primary settings for the lesson, so we
128 // need to add all the overrides.
129 $overrides = $DB->get_records('lesson_overrides', array('lessonid' => $lesson->id
));
130 // As well as the original lesson (empty override).
131 $overrides[] = new stdClass();
133 // Just do the one override.
134 $overrides = array($override);
137 foreach ($overrides as $current) {
138 $groupid = isset($current->groupid
) ?
$current->groupid
: 0;
139 $userid = isset($current->userid
) ?
$current->userid
: 0;
140 $available = isset($current->available
) ?
$current->available
: $lesson->available
;
141 $deadline = isset($current->deadline
) ?
$current->deadline
: $lesson->deadline
;
143 // Only add open/close events for an override if they differ from the lesson default.
144 $addopen = empty($current->id
) ||
!empty($current->available
);
145 $addclose = empty($current->id
) ||
!empty($current->deadline
);
147 if (!empty($lesson->coursemodule
)) {
148 $cmid = $lesson->coursemodule
;
150 $cmid = get_coursemodule_from_instance('lesson', $lesson->id
, $lesson->course
)->id
;
153 $event = new stdClass();
154 $event->description
= format_module_intro('lesson', $lesson, $cmid);
155 // Events module won't show user events when the courseid is nonzero.
156 $event->courseid
= ($userid) ?
0 : $lesson->course
;
157 $event->groupid
= $groupid;
158 $event->userid
= $userid;
159 $event->modulename
= 'lesson';
160 $event->instance
= $lesson->id
;
161 $event->timestart
= $available;
162 $event->timeduration
= max($deadline - $available, 0);
163 $event->visible
= instance_is_visible('lesson', $lesson);
164 $event->eventtype
= 'open';
166 // Determine the event name.
168 $params = new stdClass();
169 $params->lesson
= $lesson->name
;
170 $params->group
= groups_get_group_name($groupid);
171 if ($params->group
=== false) {
172 // Group doesn't exist, just skip it.
175 $eventname = get_string('overridegroupeventname', 'lesson', $params);
176 } else if ($userid) {
177 $params = new stdClass();
178 $params->lesson
= $lesson->name
;
179 $eventname = get_string('overrideusereventname', 'lesson', $params);
181 $eventname = $lesson->name
;
183 if ($addopen or $addclose) {
184 if ($deadline and $available and $event->timeduration
<= LESSON_MAX_EVENT_LENGTH
) {
185 // Single event for the whole lesson.
186 if ($oldevent = array_shift($oldevents)) {
187 $event->id
= $oldevent->id
;
191 $event->name
= $eventname;
192 // The method calendar_event::create will reuse a db record if the id field is set.
193 calendar_event
::create($event);
195 // Separate start and end events.
196 $event->timeduration
= 0;
197 if ($available && $addopen) {
198 if ($oldevent = array_shift($oldevents)) {
199 $event->id
= $oldevent->id
;
203 $event->name
= $eventname.' ('.get_string('lessonopens', 'lesson').')';
204 // The method calendar_event::create will reuse a db record if the id field is set.
205 calendar_event
::create($event);
207 if ($deadline && $addclose) {
208 if ($oldevent = array_shift($oldevents)) {
209 $event->id
= $oldevent->id
;
213 $event->name
= $eventname.' ('.get_string('lessoncloses', 'lesson').')';
214 $event->timestart
= $deadline;
215 $event->eventtype
= 'close';
216 calendar_event
::create($event);
222 // Delete any leftover events.
223 foreach ($oldevents as $badevent) {
224 $badevent = calendar_event
::load($badevent);
230 * This standard function will check all instances of this module
231 * and make sure there are up-to-date events created for each of them.
232 * If courseid = 0, then every lesson event in the site is checked, else
233 * only lesson events belonging to the course specified are checked.
234 * This function is used, in its new format, by restore_refresh_events()
236 * @param int $courseid
239 function lesson_refresh_events($courseid = 0) {
242 if ($courseid == 0) {
243 if (!$lessons = $DB->get_records('lessons')) {
247 if (!$lessons = $DB->get_records('lesson', array('course' => $courseid))) {
252 foreach ($lessons as $lesson) {
253 lesson_update_events($lesson);
260 * Given an ID of an instance of this module,
261 * this function will permanently delete the instance
262 * and any data that depends on it.
268 function lesson_delete_instance($id) {
270 require_once($CFG->dirroot
. '/mod/lesson/locallib.php');
272 $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST
);
273 $lesson = new lesson($lesson);
274 return $lesson->delete();
278 * Given a course object, this function will clean up anything that
279 * would be leftover after all the instances were deleted
282 * @param object $course an object representing the course that is being deleted
283 * @param boolean $feedback to specify if the process must output a summary of its work
286 function lesson_delete_course($course, $feedback=true) {
291 * Return a small object with summary information about what a
292 * user has done with a given particular instance of this module
293 * Used for user activity reports.
294 * $return->time = the time they did it
295 * $return->info = a short text description
298 * @param object $course
299 * @param object $user
301 * @param object $lesson
304 function lesson_user_outline($course, $user, $mod, $lesson) {
307 require_once("$CFG->libdir/gradelib.php");
308 $grades = grade_get_grades($course->id
, 'mod', 'lesson', $lesson->id
, $user->id
);
310 $return = new stdClass();
311 if (empty($grades->items
[0]->grades
)) {
312 $return->info
= get_string("no")." ".get_string("attempts", "lesson");
314 $grade = reset($grades->items
[0]->grades
);
315 $return->info
= get_string("grade") . ': ' . $grade->str_long_grade
;
317 //datesubmitted == time created. dategraded == time modified or time overridden
318 //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
319 //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
320 if ($grade->usermodified
== $user->id ||
empty($grade->datesubmitted
)) {
321 $return->time
= $grade->dategraded
;
323 $return->time
= $grade->datesubmitted
;
330 * Print a detailed representation of what a user has done with
331 * a given particular instance of this module, for user activity reports.
334 * @param object $course
335 * @param object $user
337 * @param object $lesson
340 function lesson_user_complete($course, $user, $mod, $lesson) {
341 global $DB, $OUTPUT, $CFG;
343 require_once("$CFG->libdir/gradelib.php");
345 $grades = grade_get_grades($course->id
, 'mod', 'lesson', $lesson->id
, $user->id
);
346 if (!empty($grades->items
[0]->grades
)) {
347 $grade = reset($grades->items
[0]->grades
);
348 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade
);
349 if ($grade->str_feedback
) {
350 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback
);
354 $params = array ("lessonid" => $lesson->id
, "userid" => $user->id
);
355 if ($attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params,
356 "retry, timeseen")) {
357 echo $OUTPUT->box_start();
358 $table = new html_table();
359 $table->head
= array (get_string("attemptheader", "lesson"), get_string("numberofpagesviewedheader", "lesson"),
360 get_string("numberofcorrectanswersheader", "lesson"), get_string("time"));
361 $table->width
= "100%";
362 $table->align
= array ("center", "center", "center", "center");
363 $table->size
= array ("*", "*", "*", "*");
364 $table->cellpadding
= 2;
365 $table->cellspacing
= 0;
371 foreach ($attempts as $attempt) {
372 if ($attempt->retry
== $retry) {
374 if ($attempt->correct
) {
377 $timeseen = $attempt->timeseen
;
379 $table->data
[] = array($retry +
1, $npages, $ncorrect, userdate($timeseen));
382 if ($attempt->correct
) {
390 $table->data
[] = array($retry +
1, $npages, $ncorrect, userdate($timeseen));
392 echo html_writer
::table($table);
393 echo $OUTPUT->box_end();
400 * Prints lesson summaries on MyMoodle Page
402 * Prints lesson name, due date and attempt information on
403 * lessons that have a deadline that has not already passed
404 * and it is available for taking.
409 * @uses CONTEXT_MODULE
410 * @param array $courses An array of course objects to get lesson instances from
411 * @param array $htmlarray Store overview output array( course ID => 'lesson' => HTML output )
414 function lesson_print_overview($courses, &$htmlarray) {
415 global $USER, $CFG, $DB, $OUTPUT;
417 if (!$lessons = get_all_instances_in_courses('lesson', $courses)) {
421 // Get all of the current users attempts on all lessons.
422 $params = array($USER->id
);
423 $sql = 'SELECT lessonid, userid, count(userid) as attempts
426 GROUP BY lessonid, userid';
427 $allattempts = $DB->get_records_sql($sql, $params);
428 $completedattempts = array();
429 foreach ($allattempts as $myattempt) {
430 $completedattempts[$myattempt->lessonid
] = $myattempt->attempts
;
433 // Get the current course ID.
434 $listoflessons = array();
435 foreach ($lessons as $lesson) {
436 $listoflessons[] = $lesson->id
;
438 // Get the last page viewed by the current user for every lesson in this course.
439 list($insql, $inparams) = $DB->get_in_or_equal($listoflessons, SQL_PARAMS_NAMED
);
440 $dbparams = array_merge($inparams, array('userid' => $USER->id
));
442 // Get the lesson attempts for the user that have the maximum 'timeseen' value.
443 $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.answerid as nextpageid, p.qtype ";
444 $from = "FROM {lesson_attempts} l
446 SELECT idselect.lessonid, idselect.userid, MAX(idselect.id) AS id
447 FROM {lesson_attempts} idselect
449 SELECT lessonid, userid, MAX(timeseen) AS timeseen
450 FROM {lesson_attempts}
451 WHERE userid = :userid
453 GROUP BY userid, lessonid
455 ON timeselect.timeseen = idselect.timeseen
456 AND timeselect.userid = idselect.userid
457 AND timeselect.lessonid = idselect.lessonid
458 GROUP BY idselect.userid, idselect.lessonid
461 JOIN {lesson_pages} p
462 ON l.pageid = p.id ";
463 $lastattempts = $DB->get_records_sql($select . $from, $dbparams);
465 // Now, get the lesson branches for the user that have the maximum 'timeseen' value.
466 $select = "SELECT l.id, l.timeseen, l.lessonid, l.userid, l.retry, l.pageid, l.nextpageid, p.qtype ";
467 $from = str_replace('{lesson_attempts}', '{lesson_branch}', $from);
468 $lastbranches = $DB->get_records_sql($select . $from, $dbparams);
470 $lastviewed = array();
471 foreach ($lastattempts as $lastattempt) {
472 $lastviewed[$lastattempt->lessonid
] = $lastattempt;
475 // Go through the branch times and record the 'timeseen' value if it doesn't exist
476 // for the lesson, or replace it if it exceeds the current recorded time.
477 foreach ($lastbranches as $lastbranch) {
478 if (!isset($lastviewed[$lastbranch->lessonid
])) {
479 $lastviewed[$lastbranch->lessonid
] = $lastbranch;
480 } else if ($lastviewed[$lastbranch->lessonid
]->timeseen
< $lastbranch->timeseen
) {
481 $lastviewed[$lastbranch->lessonid
] = $lastbranch;
485 // Since we have lessons in this course, now include the constants we need.
486 require_once($CFG->dirroot
. '/mod/lesson/locallib.php');
489 foreach ($lessons as $lesson) {
490 if ($lesson->deadline
!= 0 // The lesson has a deadline
491 and $lesson->deadline
>= $now // And it is before the deadline has been met
492 and ($lesson->available
== 0 or $lesson->available
<= $now)) { // And the lesson is available
495 $class = (!$lesson->visible
) ?
'dimmed' : '';
498 $context = context_module
::instance($lesson->coursemodule
);
501 $url = new moodle_url('/mod/lesson/view.php', array('id' => $lesson->coursemodule
));
502 $url = html_writer
::link($url, format_string($lesson->name
, true, array('context' => $context)), array('class' => $class));
503 $str = $OUTPUT->box(get_string('lessonname', 'lesson', $url), 'name');
506 $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline
)), 'info');
508 // Attempt information.
509 if (has_capability('mod/lesson:manage', $context)) {
510 // This is a teacher, Get the Number of user attempts.
511 $attempts = $DB->count_records('lesson_grades', array('lessonid' => $lesson->id
));
512 $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info');
513 $str = $OUTPUT->box($str, 'lesson overview');
515 // This is a student, See if the user has at least started the lesson.
516 if (isset($lastviewed[$lesson->id
]->timeseen
)) {
517 // See if the user has finished this attempt.
518 if (isset($completedattempts[$lesson->id
]) &&
519 ($completedattempts[$lesson->id
] == ($lastviewed[$lesson->id
]->retry +
1))) {
520 // Are additional attempts allowed?
521 if ($lesson->retake
) {
522 // User can retake the lesson.
523 $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info');
524 $str = $OUTPUT->box($str, 'lesson overview');
526 // User has completed the lesson and no retakes are allowed.
531 // The last attempt was not finished or the lesson does not contain questions.
532 // See if the last page viewed was a branchtable.
533 require_once($CFG->dirroot
. '/mod/lesson/pagetypes/branchtable.php');
534 if ($lastviewed[$lesson->id
]->qtype
== LESSON_PAGE_BRANCHTABLE
) {
535 // See if the next pageid is the end of lesson.
536 if ($lastviewed[$lesson->id
]->nextpageid
== LESSON_EOL
) {
537 // The last page viewed was the End of Lesson.
538 if ($lesson->retake
) {
539 // User can retake the lesson.
540 $str .= $OUTPUT->box(get_string('additionalattemptsremaining', 'lesson'), 'info');
541 $str = $OUTPUT->box($str, 'lesson overview');
543 // User has completed the lesson and no retakes are allowed.
548 // The last page viewed was NOT the end of lesson.
549 $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info');
550 $str = $OUTPUT->box($str, 'lesson overview');
554 // Last page was a question page, so the attempt is not completed yet.
555 $str .= $OUTPUT->box(get_string('notyetcompleted', 'lesson'), 'info');
556 $str = $OUTPUT->box($str, 'lesson overview');
561 // User has not yet started this lesson.
562 $str .= $OUTPUT->box(get_string('nolessonattempts', 'lesson'), 'info');
563 $str = $OUTPUT->box($str, 'lesson overview');
567 if (empty($htmlarray[$lesson->course
]['lesson'])) {
568 $htmlarray[$lesson->course
]['lesson'] = $str;
570 $htmlarray[$lesson->course
]['lesson'] .= $str;
578 * Function to be run periodically according to the moodle cron
579 * This function searches for things that need to be done, such
580 * as sending out mail, toggling flags etc ...
584 function lesson_cron () {
591 * Return grade for given user or all users.
595 * @param int $lessonid id of lesson
596 * @param int $userid optional user id, 0 means all users
597 * @return array array of grades, false if none
599 function lesson_get_user_grades($lesson, $userid=0) {
602 $params = array("lessonid" => $lesson->id
,"lessonid2" => $lesson->id
);
604 if (!empty($userid)) {
605 $params["userid"] = $userid;
606 $params["userid2"] = $userid;
607 $user = "AND u.id = :userid";
608 $fuser = "AND uu.id = :userid2";
615 if ($lesson->retake
) {
616 if ($lesson->usemaxgrade
) {
617 $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade
618 FROM {user} u, {lesson_grades} g
619 WHERE u.id = g.userid AND g.lessonid = :lessonid
623 $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade
624 FROM {user} u, {lesson_grades} g
625 WHERE u.id = g.userid AND g.lessonid = :lessonid
629 unset($params['lessonid2']);
630 unset($params['userid2']);
632 // use only first attempts (with lowest id in lesson_grades table)
633 $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted
634 FROM {user} uu, {lesson_grades} gg
635 WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2
639 $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade
640 FROM {user} u, {lesson_grades} g, ($firstonly) f
641 WHERE u.id = g.userid AND g.lessonid = :lessonid
642 AND g.id = f.firstcompleted AND g.userid=f.userid
646 return $DB->get_records_sql($sql, $params);
650 * Update grades in central gradebook
653 * @param object $lesson
654 * @param int $userid specific user only, 0 means all
655 * @param bool $nullifnone
657 function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
659 require_once($CFG->libdir
.'/gradelib.php');
661 if ($lesson->grade
== 0 ||
$lesson->practice
) {
662 lesson_grade_item_update($lesson);
664 } else if ($grades = lesson_get_user_grades($lesson, $userid)) {
665 lesson_grade_item_update($lesson, $grades);
667 } else if ($userid and $nullifnone) {
668 $grade = new stdClass();
669 $grade->userid
= $userid;
670 $grade->rawgrade
= null;
671 lesson_grade_item_update($lesson, $grade);
674 lesson_grade_item_update($lesson);
679 * Create grade item for given lesson
682 * @uses GRADE_TYPE_VALUE
683 * @uses GRADE_TYPE_NONE
684 * @param object $lesson object with extra cmidnumber
685 * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
686 * @return int 0 if ok, error code otherwise
688 function lesson_grade_item_update($lesson, $grades=null) {
690 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
691 require_once($CFG->libdir
.'/gradelib.php');
694 if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present
695 $params = array('itemname'=>$lesson->name
, 'idnumber'=>$lesson->cmidnumber
);
697 $params = array('itemname'=>$lesson->name
);
700 if (!$lesson->practice
and $lesson->grade
> 0) {
701 $params['gradetype'] = GRADE_TYPE_VALUE
;
702 $params['grademax'] = $lesson->grade
;
703 $params['grademin'] = 0;
704 } else if (!$lesson->practice
and $lesson->grade
< 0) {
705 $params['gradetype'] = GRADE_TYPE_SCALE
;
706 $params['scaleid'] = -$lesson->grade
;
708 // Make sure current grade fetched correctly from $grades
709 $currentgrade = null;
710 if (!empty($grades)) {
711 if (is_array($grades)) {
712 $currentgrade = reset($grades);
714 $currentgrade = $grades;
718 // When converting a score to a scale, use scale's grade maximum to calculate it.
719 if (!empty($currentgrade) && $currentgrade->rawgrade
!== null) {
720 $grade = grade_get_grades($lesson->course
, 'mod', 'lesson', $lesson->id
, $currentgrade->userid
);
721 $params['grademax'] = reset($grade->items
)->grademax
;
724 $params['gradetype'] = GRADE_TYPE_NONE
;
727 if ($grades === 'reset') {
728 $params['reset'] = true;
730 } else if (!empty($grades)) {
731 // Need to calculate raw grade (Note: $grades has many forms)
732 if (is_object($grades)) {
733 $grades = array($grades->userid
=> $grades);
734 } else if (array_key_exists('userid', $grades)) {
735 $grades = array($grades['userid'] => $grades);
737 foreach ($grades as $key => $grade) {
738 if (!is_array($grade)) {
739 $grades[$key] = $grade = (array) $grade;
741 //check raw grade isnt null otherwise we erroneously insert a grade of 0
742 if ($grade['rawgrade'] !== null) {
743 $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $params['grademax'] / 100);
745 //setting rawgrade to null just in case user is deleting a grade
746 $grades[$key]['rawgrade'] = null;
751 return grade_update('mod/lesson', $lesson->course
, 'mod', 'lesson', $lesson->id
, 0, $grades, $params);
755 * List the actions that correspond to a view of this module.
756 * This is used by the participation report.
758 * Note: This is not used by new logging system. Event with
759 * crud = 'r' and edulevel = LEVEL_PARTICIPATING will
760 * be considered as view action.
764 function lesson_get_view_actions() {
765 return array('view','view all');
769 * List the actions that correspond to a post of this module.
770 * This is used by the participation report.
772 * Note: This is not used by new logging system. Event with
773 * crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
774 * will be considered as post action.
778 function lesson_get_post_actions() {
779 return array('end','start');
783 * Runs any processes that must run before
784 * a lesson insert/update
787 * @param object $lesson Lesson form data
790 function lesson_process_pre_save(&$lesson) {
793 $lesson->timemodified
= time();
795 if (empty($lesson->timelimit
)) {
796 $lesson->timelimit
= 0;
798 if (empty($lesson->timespent
) or !is_numeric($lesson->timespent
) or $lesson->timespent
< 0) {
799 $lesson->timespent
= 0;
801 if (!isset($lesson->completed
)) {
802 $lesson->completed
= 0;
804 if (empty($lesson->gradebetterthan
) or !is_numeric($lesson->gradebetterthan
) or $lesson->gradebetterthan
< 0) {
805 $lesson->gradebetterthan
= 0;
806 } else if ($lesson->gradebetterthan
> 100) {
807 $lesson->gradebetterthan
= 100;
810 if (empty($lesson->width
)) {
811 $lesson->width
= 640;
813 if (empty($lesson->height
)) {
814 $lesson->height
= 480;
816 if (empty($lesson->bgcolor
)) {
817 $lesson->bgcolor
= '#FFFFFF';
820 // Conditions for dependency
821 $conditions = new stdClass
;
822 $conditions->timespent
= $lesson->timespent
;
823 $conditions->completed
= $lesson->completed
;
824 $conditions->gradebetterthan
= $lesson->gradebetterthan
;
825 $lesson->conditions
= serialize($conditions);
826 unset($lesson->timespent
);
827 unset($lesson->completed
);
828 unset($lesson->gradebetterthan
);
830 if (empty($lesson->password
)) {
831 unset($lesson->password
);
836 * Runs any processes that must be run
837 * after a lesson insert/update
840 * @param object $lesson Lesson form data
843 function lesson_process_post_save(&$lesson) {
844 // Update the events relating to this lesson.
845 lesson_update_events($lesson);
850 * Implementation of the function for printing the form elements that control
851 * whether the course reset functionality affects the lesson.
853 * @param $mform form passed by reference
855 function lesson_reset_course_form_definition(&$mform) {
856 $mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson'));
857 $mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts','lesson'));
858 $mform->addElement('advcheckbox', 'reset_lesson_user_overrides',
859 get_string('removealluseroverrides', 'lesson'));
860 $mform->addElement('advcheckbox', 'reset_lesson_group_overrides',
861 get_string('removeallgroupoverrides', 'lesson'));
865 * Course reset form defaults.
866 * @param object $course
869 function lesson_reset_course_form_defaults($course) {
870 return array('reset_lesson' => 1,
871 'reset_lesson_group_overrides' => 1,
872 'reset_lesson_user_overrides' => 1);
876 * Removes all grades from gradebook
880 * @param int $courseid
881 * @param string optional type
883 function lesson_reset_gradebook($courseid, $type='') {
886 $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
887 FROM {lesson} l, {course_modules} cm, {modules} m
888 WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course";
889 $params = array ("course" => $courseid);
890 if ($lessons = $DB->get_records_sql($sql,$params)) {
891 foreach ($lessons as $lesson) {
892 lesson_grade_item_update($lesson, 'reset');
898 * Actual implementation of the reset course functionality, delete all the
899 * lesson attempts for course $data->courseid.
903 * @param object $data the data submitted from the reset course.
904 * @return array status array
906 function lesson_reset_userdata($data) {
909 $componentstr = get_string('modulenameplural', 'lesson');
912 if (!empty($data->reset_lesson
)) {
913 $lessonssql = "SELECT l.id
915 WHERE l.course=:course";
917 $params = array ("course" => $data->courseid
);
918 $lessons = $DB->get_records_sql($lessonssql, $params);
920 // Get rid of attempts files.
921 $fs = get_file_storage();
923 foreach ($lessons as $lessonid => $unused) {
924 if (!$cm = get_coursemodule_from_instance('lesson', $lessonid)) {
927 $context = context_module
::instance($cm->id
);
928 $fs->delete_area_files($context->id
, 'mod_lesson', 'essay_responses');
932 $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params);
933 $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params);
934 $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params);
935 $DB->delete_records_select('lesson_branch', "lessonid IN ($lessonssql)", $params);
937 // remove all grades from gradebook
938 if (empty($data->reset_gradebook_grades
)) {
939 lesson_reset_gradebook($data->courseid
);
942 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false);
945 // Remove user overrides.
946 if (!empty($data->reset_lesson_user_overrides
)) {
947 $DB->delete_records_select('lesson_overrides',
948 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND userid IS NOT NULL', array($data->courseid
));
950 'component' => $componentstr,
951 'item' => get_string('useroverridesdeleted', 'lesson'),
954 // Remove group overrides.
955 if (!empty($data->reset_lesson_group_overrides
)) {
956 $DB->delete_records_select('lesson_overrides',
957 'lessonid IN (SELECT id FROM {lesson} WHERE course = ?) AND groupid IS NOT NULL', array($data->courseid
));
959 'component' => $componentstr,
960 'item' => get_string('groupoverridesdeleted', 'lesson'),
963 /// updating dates - shift may be negative too
964 if ($data->timeshift
) {
965 $DB->execute("UPDATE {lesson_overrides}
966 SET available = available + ?
967 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
968 AND available <> 0", array($data->timeshift
, $data->courseid
));
969 $DB->execute("UPDATE {lesson_overrides}
970 SET deadline = deadline + ?
971 WHERE lessonid IN (SELECT id FROM {lesson} WHERE course = ?)
972 AND deadline <> 0", array($data->timeshift
, $data->courseid
));
974 shift_course_mod_dates('lesson', array('available', 'deadline'), $data->timeshift
, $data->courseid
);
975 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
982 * Returns all other caps used in module
985 function lesson_get_extra_capabilities() {
986 return array('moodle/site:accessallgroups');
990 * @uses FEATURE_GROUPS
991 * @uses FEATURE_GROUPINGS
992 * @uses FEATURE_MOD_INTRO
993 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
994 * @uses FEATURE_GRADE_HAS_GRADE
995 * @uses FEATURE_GRADE_OUTCOMES
996 * @param string $feature FEATURE_xx constant for requested feature
997 * @return mixed True if module supports feature, false if not, null if doesn't know
999 function lesson_supports($feature) {
1001 case FEATURE_GROUPS
:
1003 case FEATURE_GROUPINGS
:
1005 case FEATURE_MOD_INTRO
:
1007 case FEATURE_COMPLETION_TRACKS_VIEWS
:
1009 case FEATURE_GRADE_HAS_GRADE
:
1011 case FEATURE_COMPLETION_HAS_RULES
:
1013 case FEATURE_GRADE_OUTCOMES
:
1015 case FEATURE_BACKUP_MOODLE2
:
1017 case FEATURE_SHOW_DESCRIPTION
:
1025 * Obtains the automatic completion state for this lesson based on any conditions
1026 * in lesson settings.
1028 * @param object $course Course
1029 * @param object $cm course-module
1030 * @param int $userid User ID
1031 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
1032 * @return bool True if completed, false if not, $type if conditions not set.
1034 function lesson_get_completion_state($course, $cm, $userid, $type) {
1037 // Get lesson details.
1038 $lesson = $DB->get_record('lesson', array('id' => $cm->instance
), '*',
1041 $result = $type; // Default return value.
1042 // If completion option is enabled, evaluate it and return true/false.
1043 if ($lesson->completionendreached
) {
1044 $value = $DB->record_exists('lesson_timer', array(
1045 'lessonid' => $lesson->id
, 'userid' => $userid, 'completed' => 1));
1046 if ($type == COMPLETION_AND
) {
1047 $result = $result && $value;
1049 $result = $result ||
$value;
1052 if ($lesson->completiontimespent
!= 0) {
1053 $duration = $DB->get_field_sql(
1054 "SELECT SUM(lessontime - starttime)
1056 WHERE lessonid = :lessonid
1057 AND userid = :userid",
1058 array('userid' => $userid, 'lessonid' => $lesson->id
));
1062 if ($type == COMPLETION_AND
) {
1063 $result = $result && ($lesson->completiontimespent
< $duration);
1065 $result = $result ||
($lesson->completiontimespent
< $duration);
1071 * This function extends the settings navigation block for the site.
1073 * It is safe to rely on PAGE here as we will only ever be within the module
1074 * context when this is called
1076 * @param settings_navigation $settings
1077 * @param navigation_node $lessonnode
1079 function lesson_extend_settings_navigation($settings, $lessonnode) {
1082 // We want to add these new nodes after the Edit settings node, and before the
1083 // Locally assigned roles node. Of course, both of those are controlled by capabilities.
1084 $keys = $lessonnode->get_children_key_list();
1086 $i = array_search('modedit', $keys);
1087 if ($i === false and array_key_exists(0, $keys)) {
1088 $beforekey = $keys[0];
1089 } else if (array_key_exists($i +
1, $keys)) {
1090 $beforekey = $keys[$i +
1];
1093 if (has_capability('mod/lesson:manageoverrides', $PAGE->cm
->context
)) {
1094 $url = new moodle_url('/mod/lesson/overrides.php', array('cmid' => $PAGE->cm
->id
));
1095 $node = navigation_node
::create(get_string('groupoverrides', 'lesson'),
1096 new moodle_url($url, array('mode' => 'group')),
1097 navigation_node
::TYPE_SETTING
, null, 'mod_lesson_groupoverrides');
1098 $lessonnode->add_node($node, $beforekey);
1100 $node = navigation_node
::create(get_string('useroverrides', 'lesson'),
1101 new moodle_url($url, array('mode' => 'user')),
1102 navigation_node
::TYPE_SETTING
, null, 'mod_lesson_useroverrides');
1103 $lessonnode->add_node($node, $beforekey);
1106 if (has_capability('mod/lesson:edit', $PAGE->cm
->context
)) {
1107 $url = new moodle_url('/mod/lesson/view.php', array('id' => $PAGE->cm
->id
));
1108 $lessonnode->add(get_string('preview', 'lesson'), $url);
1109 $editnode = $lessonnode->add(get_string('edit', 'lesson'));
1110 $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm
->id
, 'mode' => 'collapsed'));
1111 $editnode->add(get_string('collapsed', 'lesson'), $url);
1112 $url = new moodle_url('/mod/lesson/edit.php', array('id' => $PAGE->cm
->id
, 'mode' => 'full'));
1113 $editnode->add(get_string('full', 'lesson'), $url);
1116 if (has_capability('mod/lesson:viewreports', $PAGE->cm
->context
)) {
1117 $reportsnode = $lessonnode->add(get_string('reports', 'lesson'));
1118 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm
->id
, 'action'=>'reportoverview'));
1119 $reportsnode->add(get_string('overview', 'lesson'), $url);
1120 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm
->id
, 'action'=>'reportdetail'));
1121 $reportsnode->add(get_string('detailedstats', 'lesson'), $url);
1124 if (has_capability('mod/lesson:grade', $PAGE->cm
->context
)) {
1125 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm
->id
));
1126 $lessonnode->add(get_string('manualgrading', 'lesson'), $url);
1132 * Get list of available import or export formats
1134 * Copied and modified from lib/questionlib.php
1136 * @param string $type 'import' if import list, otherwise export list assumed
1137 * @return array sorted list of import/export formats available
1139 function lesson_get_import_export_formats($type) {
1141 $fileformats = core_component
::get_plugin_list("qformat");
1143 $fileformatname=array();
1144 foreach ($fileformats as $fileformat=>$fdir) {
1145 $format_file = "$fdir/format.php";
1146 if (file_exists($format_file) ) {
1147 require_once($format_file);
1151 $classname = "qformat_$fileformat";
1152 $format_class = new $classname();
1153 if ($type=='import') {
1154 $provided = $format_class->provide_import();
1156 $provided = $format_class->provide_export();
1159 $fileformatnames[$fileformat] = get_string('pluginname', 'qformat_'.$fileformat);
1162 natcasesort($fileformatnames);
1164 return $fileformatnames;
1168 * Serves the lesson attachments. Implements needed access control ;-)
1170 * @package mod_lesson
1172 * @param stdClass $course course object
1173 * @param stdClass $cm course module object
1174 * @param stdClass $context context object
1175 * @param string $filearea file area
1176 * @param array $args extra arguments
1177 * @param bool $forcedownload whether or not force download
1178 * @param array $options additional options affecting the file serving
1179 * @return bool false if file not found, does not return if found - justsend the file
1181 function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
1184 if ($context->contextlevel
!= CONTEXT_MODULE
) {
1188 $fileareas = lesson_get_file_areas();
1189 if (!array_key_exists($filearea, $fileareas)) {
1193 if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance
))) {
1197 require_course_login($course, true, $cm);
1199 if ($filearea === 'page_contents') {
1200 $pageid = (int)array_shift($args);
1201 if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) {
1204 $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args);
1206 } else if ($filearea === 'page_answers' ||
$filearea === 'page_responses') {
1207 $itemid = (int)array_shift($args);
1208 if (!$pageanswers = $DB->get_record('lesson_answers', array('id' => $itemid))) {
1211 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1213 } else if ($filearea === 'essay_responses') {
1214 $itemid = (int)array_shift($args);
1215 if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $itemid))) {
1218 $fullpath = "/$context->id/mod_lesson/$filearea/$itemid/".implode('/', $args);
1220 } else if ($filearea === 'mediafile') {
1221 if (count($args) > 1) {
1222 // Remove the itemid when it appears to be part of the arguments. If there is only one argument
1223 // then it is surely the file name. The itemid is sometimes used to prevent browser caching.
1226 $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args);
1232 $fs = get_file_storage();
1233 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1237 // finally send the file
1238 send_stored_file($file, 0, 0, $forcedownload, $options); // download MUST be forced - security!
1242 * Returns an array of file areas
1244 * @package mod_lesson
1246 * @return array a list of available file areas
1248 function lesson_get_file_areas() {
1250 $areas['page_contents'] = get_string('pagecontents', 'mod_lesson');
1251 $areas['mediafile'] = get_string('mediafile', 'mod_lesson');
1252 $areas['page_answers'] = get_string('pageanswers', 'mod_lesson');
1253 $areas['page_responses'] = get_string('pageresponses', 'mod_lesson');
1254 $areas['essay_responses'] = get_string('essayresponses', 'mod_lesson');
1259 * Returns a file_info_stored object for the file being requested here
1261 * @package mod_lesson
1263 * @global stdClass $CFG
1264 * @param file_browse $browser file browser instance
1265 * @param array $areas file areas
1266 * @param stdClass $course course object
1267 * @param stdClass $cm course module object
1268 * @param stdClass $context context object
1269 * @param string $filearea file area
1270 * @param int $itemid item ID
1271 * @param string $filepath file path
1272 * @param string $filename file name
1273 * @return file_info_stored
1275 function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
1278 if (!has_capability('moodle/course:managefiles', $context)) {
1279 // No peaking here for students!
1283 // Mediafile area does not have sub directories, so let's select the default itemid to prevent
1284 // the user from selecting a directory to access the mediafile content.
1285 if ($filearea == 'mediafile' && is_null($itemid)) {
1289 if (is_null($itemid)) {
1290 return new mod_lesson_file_info($browser, $course, $cm, $context, $areas, $filearea);
1293 $fs = get_file_storage();
1294 $filepath = is_null($filepath) ?
'/' : $filepath;
1295 $filename = is_null($filename) ?
'.' : $filename;
1296 if (!$storedfile = $fs->get_file($context->id
, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) {
1300 $itemname = $filearea;
1301 if ($filearea == 'page_contents') {
1302 $itemname = $DB->get_field('lesson_pages', 'title', array('lessonid' => $cm->instance
, 'id' => $itemid));
1303 $itemname = format_string($itemname, true, array('context' => $context));
1305 $areas = lesson_get_file_areas();
1306 if (isset($areas[$filearea])) {
1307 $itemname = $areas[$filearea];
1311 $urlbase = $CFG->wwwroot
. '/pluginfile.php';
1312 return new file_info_stored($browser, $context, $storedfile, $urlbase, $itemname, $itemid, true, true, false);
1317 * Return a list of page types
1318 * @param string $pagetype current page type
1319 * @param stdClass $parentcontext Block's parent context
1320 * @param stdClass $currentcontext Current context of block
1322 function lesson_page_type_list($pagetype, $parentcontext, $currentcontext) {
1323 $module_pagetype = array(
1324 'mod-lesson-*'=>get_string('page-mod-lesson-x', 'lesson'),
1325 'mod-lesson-view'=>get_string('page-mod-lesson-view', 'lesson'),
1326 'mod-lesson-edit'=>get_string('page-mod-lesson-edit', 'lesson'));
1327 return $module_pagetype;
1331 * Update the lesson activity to include any file
1332 * that was uploaded, or if there is none, set the
1333 * mediafile field to blank.
1335 * @param int $lessonid the lesson id
1336 * @param stdClass $context the context
1337 * @param int $draftitemid the draft item
1339 function lesson_update_media_file($lessonid, $context, $draftitemid) {
1342 // Set the filestorage object.
1343 $fs = get_file_storage();
1344 // Save the file if it exists that is currently in the draft area.
1345 file_save_draft_area_files($draftitemid, $context->id
, 'mod_lesson', 'mediafile', 0);
1346 // Get the file if it exists.
1347 $files = $fs->get_area_files($context->id
, 'mod_lesson', 'mediafile', 0, 'itemid, filepath, filename', false);
1348 // Check that there is a file to process.
1349 if (count($files) == 1) {
1350 // Get the first (and only) file.
1351 $file = reset($files);
1352 // Set the mediafile column in the lessons table.
1353 $DB->set_field('lesson', 'mediafile', '/' . $file->get_filename(), array('id' => $lessonid));
1355 // Set the mediafile column in the lessons table.
1356 $DB->set_field('lesson', 'mediafile', '', array('id' => $lessonid));