Merge branch 'MDL-26768_0_grade' of git://github.com/andyjdavis/moodle
[moodle.git] / mod / lesson / lib.php
CommitLineData
8cc86111 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
5491947a 18/**
19 * Standard library of functions and constants for lesson
20 *
cc3dbaaa
PS
21 * @package mod
22 * @subpackage lesson
8d1a3963 23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
cc3dbaaa 24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5491947a 25 **/
97c44107 26
28f5bf67
PS
27defined('MOODLE_INTERNAL') || die();
28
1e7f8ea2 29/* Do not include any libraries here! */
97c44107 30
acf85537 31/**
32 * Given an object containing all the necessary data,
33 * (defined by the form in mod_form.php) this function
34 * will create a new instance and return the id number
35 * of the new instance.
36 *
8cc86111 37 * @global object
38 * @global object
acf85537 39 * @param object $lesson Lesson post data from the form
40 * @return int
41 **/
0a4abb73 42function lesson_add_instance($data, $mform) {
1e7f8ea2 43 global $DB;
bbcbc0fe 44
0a4abb73 45 $cmid = $data->coursemodule;
5f649aaa 46
0a4abb73 47 lesson_process_pre_save($data);
271fea97 48
0a4abb73
SH
49 unset($data->mediafile);
50 $lessonid = $DB->insert_record("lesson", $data);
51 $data->id = $lessonid;
97c44107 52
0a4abb73
SH
53 $context = get_context_instance(CONTEXT_MODULE, $cmid);
54 $lesson = $DB->get_record('lesson', array('id'=>$lessonid), '*', MUST_EXIST);
55
3d1b7452
PS
56 if ($filename = $mform->get_new_filename('mediafilepicker')) {
57 if ($file = $mform->save_stored_file('mediafilepicker', $context->id, 'mod_lesson', 'mediafile', 0, '/', $filename)) {
8d1a3963 58 $DB->set_field('lesson', 'mediafile', '/'.$file->get_filename(), array('id'=>$lesson->id));
0a4abb73
SH
59 }
60 }
61
62 lesson_process_post_save($data);
63
64 lesson_grade_item_update($data);
92bcca38 65
97c44107 66 return $lesson->id;
bbcbc0fe 67}
68
acf85537 69/**
70 * Given an object containing all the necessary data,
71 * (defined by the form in mod_form.php) this function
72 * will update an existing instance with new data.
73 *
8cc86111 74 * @global object
acf85537 75 * @param object $lesson Lesson post data from the form
76 * @return boolean
77 **/
0a4abb73 78function lesson_update_instance($data, $mform) {
c18269c7 79 global $DB;
bbcbc0fe 80
0a4abb73
SH
81 $data->id = $data->instance;
82 $cmid = $data->coursemodule;
1535c81b 83
0a4abb73 84 lesson_process_pre_save($data);
97c44107 85
0a4abb73 86 unset($data->mediafile);
1e7f8ea2 87 $DB->update_record("lesson", $data);
97c44107 88
0a4abb73 89 $context = get_context_instance(CONTEXT_MODULE, $cmid);
3d1b7452
PS
90 if ($filename = $mform->get_new_filename('mediafilepicker')) {
91 if ($file = $mform->save_stored_file('mediafilepicker', $context->id, 'mod_lesson', 'mediafile', 0, '/', $filename, true)) {
8d1a3963 92 $DB->set_field('lesson', 'mediafile', '/'.$file->get_filename(), array('id'=>$data->id));
3d1b7452
PS
93 } else {
94 $DB->set_field('lesson', 'mediafile', '', array('id'=>$data->id));
0a4abb73 95 }
3d1b7452
PS
96 } else {
97 $DB->set_field('lesson', 'mediafile', '', array('id'=>$data->id));
0a4abb73
SH
98 }
99
100 lesson_process_post_save($data);
92bcca38 101
102 // update grade item definition
0a4abb73 103 lesson_grade_item_update($data);
92bcca38 104
105 // update grades - TODO: do it only when grading style changes
0a4abb73 106 lesson_update_grades($data, 0, false);
92bcca38 107
1e7f8ea2 108 return true;
bbcbc0fe 109}
110
111
8cc86111 112/**
113 * Given an ID of an instance of this module,
114 * this function will permanently delete the instance
115 * and any data that depends on it.
116 *
117 * @global object
118 * @param int $id
119 * @return bool
120 */
bbcbc0fe 121function lesson_delete_instance($id) {
3d53d99e
PS
122 global $DB, $CFG;
123 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
124
0a4abb73
SH
125 $lesson = $DB->get_record("lesson", array("id"=>$id), '*', MUST_EXIST);
126 $lesson = new lesson($lesson);
127 return $lesson->delete();
bbcbc0fe 128}
129
eee85098 130/**
131 * Given a course object, this function will clean up anything that
0a4abb73 132 * would be leftover after all the instances were deleted
eee85098 133 *
8cc86111 134 * @global object
eee85098 135 * @param object $course an object representing the course that is being deleted
136 * @param boolean $feedback to specify if the process must output a summary of its work
137 * @return boolean
138 */
139function lesson_delete_course($course, $feedback=true) {
eee85098 140 return true;
141}
142
8cc86111 143/**
144 * Return a small object with summary information about what a
145 * user has done with a given particular instance of this module
146 * Used for user activity reports.
147 * $return->time = the time they did it
148 * $return->info = a short text description
149 *
150 * @global object
151 * @param object $course
152 * @param object $user
153 * @param object $mod
154 * @param object $lesson
155 * @return object
156 */
bbcbc0fe 157function lesson_user_outline($course, $user, $mod, $lesson) {
1a96363a 158 global $CFG;
df0442c6 159
1a96363a
NC
160 require_once("$CFG->libdir/gradelib.php");
161 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
162
39790bd8 163 $return = new stdClass();
1a96363a
NC
164 if (empty($grades->items[0]->grades)) {
165 $return->info = get_string("no")." ".get_string("attempts", "lesson");
bbcbc0fe 166 } else {
1a96363a
NC
167 $grade = reset($grades->items[0]->grades);
168 $return->info = get_string("grade") . ': ' . $grade->str_long_grade;
169 $return->time = $grade->dategraded;
bbcbc0fe 170 $return->info = get_string("no")." ".get_string("attempts", "lesson");
171 }
172 return $return;
173}
174
8cc86111 175/**
176 * Print a detailed representation of what a user has done with
177 * a given particular instance of this module, for user activity reports.
178 *
179 * @global object
180 * @param object $course
181 * @param object $user
182 * @param object $mod
183 * @param object $lesson
184 * @return bool
185 */
bbcbc0fe 186function lesson_user_complete($course, $user, $mod, $lesson) {
1a96363a
NC
187 global $DB, $OUTPUT, $CFG;
188
189 require_once("$CFG->libdir/gradelib.php");
190
191 $grades = grade_get_grades($course->id, 'mod', 'lesson', $lesson->id, $user->id);
192 if (!empty($grades->items[0]->grades)) {
193 $grade = reset($grades->items[0]->grades);
194 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
195 if ($grade->str_feedback) {
196 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
197 }
198 }
fe75e76b 199
646fc290 200 $params = array ("lessonid" => $lesson->id, "userid" => $user->id);
201 if ($attempts = $DB->get_records_select("lesson_attempts", "lessonid = :lessonid AND userid = :userid", $params,
bbcbc0fe 202 "retry, timeseen")) {
d68ccdba 203 echo $OUTPUT->box_start();
3ab269ed 204 $table = new html_table();
ac8e16be 205 $table->head = array (get_string("attempt", "lesson"), get_string("numberofpagesviewed", "lesson"),
206 get_string("numberofcorrectanswers", "lesson"), get_string("time"));
207 $table->width = "100%";
208 $table->align = array ("center", "center", "center", "center");
209 $table->size = array ("*", "*", "*", "*");
210 $table->cellpadding = 2;
211 $table->cellspacing = 0;
bbcbc0fe 212
213 $retry = 0;
214 $npages = 0;
215 $ncorrect = 0;
5f649aaa 216
ac8e16be 217 foreach ($attempts as $attempt) {
218 if ($attempt->retry == $retry) {
219 $npages++;
bbcbc0fe 220 if ($attempt->correct) {
221 $ncorrect++;
222 }
223 $timeseen = $attempt->timeseen;
224 } else {
ac8e16be 225 $table->data[] = array($retry + 1, $npages, $ncorrect, userdate($timeseen));
bbcbc0fe 226 $retry++;
227 $npages = 1;
228 if ($attempt->correct) {
229 $ncorrect = 1;
230 } else {
231 $ncorrect = 0;
232 }
ac8e16be 233 }
234 }
bbcbc0fe 235 if ($npages) {
ac8e16be 236 $table->data[] = array($retry + 1, $npages, $ncorrect, userdate($timeseen));
bbcbc0fe 237 }
16be8974 238 echo html_writer::table($table);
d68ccdba 239 echo $OUTPUT->box_end();
bbcbc0fe 240 }
241
bbcbc0fe 242 return true;
243}
244
4342dc32 245/**
246 * Prints lesson summaries on MyMoodle Page
247 *
248 * Prints lesson name, due date and attempt information on
249 * lessons that have a deadline that has not already passed
250 * and it is available for taking.
251 *
8cc86111 252 * @global object
253 * @global stdClass
254 * @global object
255 * @uses CONTEXT_MODULE
4342dc32 256 * @param array $courses An array of course objects to get lesson instances from
257 * @param array $htmlarray Store overview output array( course ID => 'lesson' => HTML output )
8cc86111 258 * @return void
4342dc32 259 */
260function lesson_print_overview($courses, &$htmlarray) {
fe75e76b 261 global $USER, $CFG, $DB, $OUTPUT;
4342dc32 262
263 if (!$lessons = get_all_instances_in_courses('lesson', $courses)) {
264 return;
265 }
266
267/// Get Necessary Strings
268 $strlesson = get_string('modulename', 'lesson');
269 $strnotattempted = get_string('nolessonattempts', 'lesson');
270 $strattempted = get_string('lessonattempted', 'lesson');
271
272 $now = time();
273 foreach ($lessons as $lesson) {
274 if ($lesson->deadline != 0 // The lesson has a deadline
275 and $lesson->deadline >= $now // And it is before the deadline has been met
276 and ($lesson->available == 0 or $lesson->available <= $now)) { // And the lesson is available
277
278 // Lesson name
279 if (!$lesson->visible) {
280 $class = ' class="dimmed"';
281 } else {
282 $class = '';
283 }
fe75e76b 284 $str = $OUTPUT->box("$strlesson: <a$class href=\"$CFG->wwwroot/mod/lesson/view.php?id=$lesson->coursemodule\">".
285 format_string($lesson->name).'</a>', 'name');
4342dc32 286
287 // Deadline
fe75e76b 288 $str .= $OUTPUT->box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info');
4342dc32 289
290 // Attempt information
291 if (has_capability('mod/lesson:manage', get_context_instance(CONTEXT_MODULE, $lesson->coursemodule))) {
292 // Number of user attempts
318e3745 293 $attempts = $DB->count_records('lesson_attempts', array('lessonid'=>$lesson->id));
fe75e76b 294 $str .= $OUTPUT->box(get_string('xattempts', 'lesson', $attempts), 'info');
4342dc32 295 } else {
296 // Determine if the user has attempted the lesson or not
318e3745 297 if ($DB->count_records('lesson_attempts', array('lessonid'=>$lesson->id, 'userid'=>$USER->id))) {
fe75e76b 298 $str .= $OUTPUT->box($strattempted, 'info');
4342dc32 299 } else {
fe75e76b 300 $str .= $OUTPUT->box($strnotattempted, 'info');
4342dc32 301 }
302 }
fe75e76b 303 $str = $OUTPUT->box($str, 'lesson overview');
4342dc32 304
305 if (empty($htmlarray[$lesson->course]['lesson'])) {
306 $htmlarray[$lesson->course]['lesson'] = $str;
307 } else {
308 $htmlarray[$lesson->course]['lesson'] .= $str;
309 }
310 }
311 }
312}
313
8cc86111 314/**
315 * Function to be run periodically according to the moodle cron
316 * This function searches for things that need to be done, such
317 * as sending out mail, toggling flags etc ...
318 * @global stdClass
319 * @return bool true
320 */
bbcbc0fe 321function lesson_cron () {
bbcbc0fe 322 global $CFG;
323
324 return true;
325}
326
92bcca38 327/**
328 * Return grade for given user or all users.
329 *
8cc86111 330 * @global stdClass
331 * @global object
92bcca38 332 * @param int $lessonid id of lesson
333 * @param int $userid optional user id, 0 means all users
334 * @return array array of grades, false if none
335 */
336function lesson_get_user_grades($lesson, $userid=0) {
646fc290 337 global $CFG, $DB;
bbcbc0fe 338
b920f6e8 339 $params = array("lessonid" => $lesson->id,"lessonid2" => $lesson->id);
fe75e76b 340
646fc290 341 if (isset($userid)) {
342 $params["userid"] = $userid;
b920f6e8 343 $params["userid2"] = $userid;
646fc290 344 $user = "AND u.id = :userid";
b920f6e8 345 $fuser = "AND uu.id = :userid2";
646fc290 346 }
347 else {
e57bc529 348 $user="";
646fc290 349 $fuser="";
350 }
fe75e76b 351
512ce792 352 if ($lesson->retake) {
353 if ($lesson->usemaxgrade) {
ac9b0805 354 $sql = "SELECT u.id, u.id AS userid, MAX(g.grade) AS rawgrade
646fc290 355 FROM {user} u, {lesson_grades} g
356 WHERE u.id = g.userid AND g.lessonid = :lessonid
92bcca38 357 $user
358 GROUP BY u.id";
512ce792 359 } else {
ac9b0805 360 $sql = "SELECT u.id, u.id AS userid, AVG(g.grade) AS rawgrade
646fc290 361 FROM {user} u, {lesson_grades} g
362 WHERE u.id = g.userid AND g.lessonid = :lessonid
92bcca38 363 $user
364 GROUP BY u.id";
512ce792 365 }
96fa52a4 366 unset($params['lessonid2']);
367 unset($params['userid2']);
512ce792 368 } else {
92bcca38 369 // use only first attempts (with lowest id in lesson_grades table)
370 $firstonly = "SELECT uu.id AS userid, MIN(gg.id) AS firstcompleted
646fc290 371 FROM {user} uu, {lesson_grades} gg
b920f6e8 372 WHERE uu.id = gg.userid AND gg.lessonid = :lessonid2
92bcca38 373 $fuser
374 GROUP BY uu.id";
375
ac9b0805 376 $sql = "SELECT u.id, u.id AS userid, g.grade AS rawgrade
646fc290 377 FROM {user} u, {lesson_grades} g, ($firstonly) f
378 WHERE u.id = g.userid AND g.lessonid = :lessonid
92bcca38 379 AND g.id = f.firstcompleted AND g.userid=f.userid
380 $user";
381 }
382
646fc290 383 return $DB->get_records_sql($sql, $params);
92bcca38 384}
385
386/**
387 * Update grades in central gradebook
388 *
8cc86111 389 * @global stdclass
390 * @global object
775f811a 391 * @param object $lesson
392 * @param int $userid specific user only, 0 means all
8cc86111 393 * @param bool $nullifnone
92bcca38 394 */
775f811a 395function lesson_update_grades($lesson, $userid=0, $nullifnone=true) {
646fc290 396 global $CFG, $DB;
775f811a 397 require_once($CFG->libdir.'/gradelib.php');
92bcca38 398
775f811a 399 if ($lesson->grade == 0) {
400 lesson_grade_item_update($lesson);
92bcca38 401
775f811a 402 } else if ($grades = lesson_get_user_grades($lesson, $userid)) {
403 lesson_grade_item_update($lesson, $grades);
eafb9d9e 404
775f811a 405 } else if ($userid and $nullifnone) {
39790bd8 406 $grade = new stdClass();
775f811a 407 $grade->userid = $userid;
408 $grade->rawgrade = NULL;
409 lesson_grade_item_update($lesson, $grade);
92bcca38 410
411 } else {
775f811a 412 lesson_grade_item_update($lesson);
413 }
414}
415
416/**
417 * Update all grades in gradebook.
8cc86111 418 *
419 * @global object
775f811a 420 */
421function lesson_upgrade_grades() {
422 global $DB;
423
424 $sql = "SELECT COUNT('x')
425 FROM {lesson} l, {course_modules} cm, {modules} m
426 WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id";
427 $count = $DB->count_records_sql($sql);
428
429 $sql = "SELECT l.*, cm.idnumber AS cmidnumber, l.course AS courseid
430 FROM {lesson} l, {course_modules} cm, {modules} m
431 WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id";
a8307c22
EL
432 $rs = $DB->get_recordset_sql($sql);
433 if ($rs->valid()) {
775f811a 434 $pbar = new progress_bar('lessonupgradegrades', 500, true);
435 $i=0;
436 foreach ($rs as $lesson) {
437 $i++;
438 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
439 lesson_update_grades($lesson, 0, false);
440 $pbar->update($i, $count, "Updating Lesson grades ($i/$count).");
ac8e16be 441 }
92bcca38 442 }
a8307c22 443 $rs->close();
92bcca38 444}
5f649aaa 445
92bcca38 446/**
447 * Create grade item for given lesson
448 *
8cc86111 449 * @global stdClass
450 * @uses GRADE_TYPE_VALUE
451 * @uses GRADE_TYPE_NONE
92bcca38 452 * @param object $lesson object with extra cmidnumber
8cc86111 453 * @param array|object $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
92bcca38 454 * @return int 0 if ok, error code otherwise
455 */
0b5a80a1 456function lesson_grade_item_update($lesson, $grades=NULL) {
92bcca38 457 global $CFG;
458 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
459 require_once($CFG->libdir.'/gradelib.php');
460 }
461
462 if (array_key_exists('cmidnumber', $lesson)) { //it may not be always present
463 $params = array('itemname'=>$lesson->name, 'idnumber'=>$lesson->cmidnumber);
ac8e16be 464 } else {
92bcca38 465 $params = array('itemname'=>$lesson->name);
ac8e16be 466 }
92bcca38 467
468 if ($lesson->grade > 0) {
469 $params['gradetype'] = GRADE_TYPE_VALUE;
91ca18e8 470 $params['grademax'] = $lesson->grade;
92bcca38 471 $params['grademin'] = 0;
92bcca38 472 } else {
473 $params['gradetype'] = GRADE_TYPE_NONE;
92bcca38 474 }
475
0b5a80a1 476 if ($grades === 'reset') {
477 $params['reset'] = true;
478 $grades = NULL;
13b92708 479 } else if (!empty($grades)) {
480 // Need to calculate raw grade (Note: $grades has many forms)
481 if (is_object($grades)) {
482 $grades = array($grades->userid => $grades);
483 } else if (array_key_exists('userid', $grades)) {
484 $grades = array($grades['userid'] => $grades);
485 }
486 foreach ($grades as $key => $grade) {
487 if (!is_array($grade)) {
488 $grades[$key] = $grade = (array) $grade;
489 }
76027a9f
AD
490 //check raw grade isnt null otherwise we erroneously insert a grade of 0
491 if ($grade['rawgrade'] !== null) {
492 $grades[$key]['rawgrade'] = ($grade['rawgrade'] * $lesson->grade / 100);
493 } else {
494 //setting rawgrade to null just in case user is deleting a grade
495 $grades[$key]['rawgrade'] = null;
496 }
13b92708 497 }
0b5a80a1 498 }
499
500 return grade_update('mod/lesson', $lesson->course, 'mod', 'lesson', $lesson->id, 0, $grades, $params);
92bcca38 501}
502
503/**
504 * Delete grade item for given lesson
505 *
8cc86111 506 * @global stdClass
92bcca38 507 * @param object $lesson object
508 * @return object lesson
509 */
510function lesson_grade_item_delete($lesson) {
511 global $CFG;
2f67a9b3 512
bbcbc0fe 513}
514
92bcca38 515
8cc86111 516/**
517 * Must return an array of user records (all data) who are participants
518 * for a given instance of lesson. Must include every user involved
1e7f8ea2 519 * in the instance, independent of his role (student, teacher, admin...)
8cc86111 520 *
521 * @global stdClass
522 * @global object
523 * @param int $lessonid
524 * @return array
525 */
bbcbc0fe 526function lesson_get_participants($lessonid) {
646fc290 527 global $CFG, $DB;
5f649aaa 528
6e773096 529 //Get students
646fc290 530 $params = array ("lessonid" => $lessonid);
531 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
532 FROM {user} u,
533 {lesson_attempts} a
534 WHERE a.lessonid = :lessonid and
535 u.id = a.userid", $params);
6e773096 536
537 //Return students array (it contains an array of unique users)
538 return ($students);
bbcbc0fe 539}
f3221af9 540
8cc86111 541/**
542 * @return array
543 */
f3221af9 544function lesson_get_view_actions() {
545 return array('view','view all');
546}
547
8cc86111 548/**
549 * @return array
550 */
f3221af9 551function lesson_get_post_actions() {
0a4abb73 552 return array('end','start');
f3221af9 553}
554
acf85537 555/**
556 * Runs any processes that must run before
557 * a lesson insert/update
558 *
8cc86111 559 * @global object
acf85537 560 * @param object $lesson Lesson form data
561 * @return void
562 **/
563function lesson_process_pre_save(&$lesson) {
646fc290 564 global $DB;
fe75e76b 565
acf85537 566 $lesson->timemodified = time();
567
862bd9cd 568 if (empty($lesson->timed)) {
569 $lesson->timed = 0;
570 }
acf85537 571 if (empty($lesson->timespent) or !is_numeric($lesson->timespent) or $lesson->timespent < 0) {
572 $lesson->timespent = 0;
573 }
574 if (!isset($lesson->completed)) {
575 $lesson->completed = 0;
576 }
577 if (empty($lesson->gradebetterthan) or !is_numeric($lesson->gradebetterthan) or $lesson->gradebetterthan < 0) {
578 $lesson->gradebetterthan = 0;
579 } else if ($lesson->gradebetterthan > 100) {
580 $lesson->gradebetterthan = 100;
581 }
582
0a4abb73
SH
583 if (empty($lesson->width)) {
584 $lesson->width = 640;
585 }
586 if (empty($lesson->height)) {
587 $lesson->height = 480;
588 }
589 if (empty($lesson->bgcolor)) {
590 $lesson->bgcolor = '#FFFFFF';
591 }
592
acf85537 593 // Conditions for dependency
594 $conditions = new stdClass;
595 $conditions->timespent = $lesson->timespent;
596 $conditions->completed = $lesson->completed;
597 $conditions->gradebetterthan = $lesson->gradebetterthan;
646fc290 598 $lesson->conditions = serialize($conditions);
acf85537 599 unset($lesson->timespent);
600 unset($lesson->completed);
601 unset($lesson->gradebetterthan);
602
4d22ec81 603 if (empty($lesson->password)) {
acf85537 604 unset($lesson->password);
605 }
acf85537 606}
607
608/**
609 * Runs any processes that must be run
610 * after a lesson insert/update
611 *
8cc86111 612 * @global object
acf85537 613 * @param object $lesson Lesson form data
614 * @return void
615 **/
616function lesson_process_post_save(&$lesson) {
1e7f8ea2
PS
617 global $DB, $CFG;
618 require_once($CFG->dirroot.'/calendar/lib.php');
619 require_once($CFG->dirroot . '/mod/lesson/locallib.php');
c18269c7 620
621 if ($events = $DB->get_records('event', array('modulename'=>'lesson', 'instance'=>$lesson->id))) {
acf85537 622 foreach($events as $event) {
0a4abb73
SH
623 $event = calendar_event::load($event->id);
624 $event->delete();
acf85537 625 }
626 }
627
628 $event = new stdClass;
629 $event->description = $lesson->name;
630 $event->courseid = $lesson->course;
631 $event->groupid = 0;
632 $event->userid = 0;
633 $event->modulename = 'lesson';
634 $event->instance = $lesson->id;
635 $event->eventtype = 'open';
636 $event->timestart = $lesson->available;
fe75e76b 637
acf85537 638 $event->visible = instance_is_visible('lesson', $lesson);
fe75e76b 639
acf85537 640 $event->timeduration = ($lesson->deadline - $lesson->available);
641
642 if ($lesson->deadline and $lesson->available and $event->timeduration <= LESSON_MAX_EVENT_LENGTH) {
643 // Single event for the whole lesson.
644 $event->name = $lesson->name;
0a4abb73 645 calendar_event::create(clone($event));
acf85537 646 } else {
647 // Separate start and end events.
648 $event->timeduration = 0;
649 if ($lesson->available) {
650 $event->name = $lesson->name.' ('.get_string('lessonopens', 'lesson').')';
0a4abb73
SH
651 calendar_event::create(clone($event));
652 } else if ($lesson->deadline) {
acf85537 653 $event->name = $lesson->name.' ('.get_string('lessoncloses', 'lesson').')';
654 $event->timestart = $lesson->deadline;
655 $event->eventtype = 'close';
0a4abb73 656 calendar_event::create(clone($event));
acf85537 657 }
658 }
659}
660
0b5a80a1 661
662/**
663 * Implementation of the function for printing the form elements that control
664 * whether the course reset functionality affects the lesson.
fe75e76b 665 *
0b5a80a1 666 * @param $mform form passed by reference
667 */
668function lesson_reset_course_form_definition(&$mform) {
669 $mform->addElement('header', 'lessonheader', get_string('modulenameplural', 'lesson'));
670 $mform->addElement('advcheckbox', 'reset_lesson', get_string('deleteallattempts','lesson'));
671}
672
673/**
674 * Course reset form defaults.
8cc86111 675 * @param object $course
676 * @return array
0b5a80a1 677 */
678function lesson_reset_course_form_defaults($course) {
679 return array('reset_lesson'=>1);
680}
681
682/**
683 * Removes all grades from gradebook
8cc86111 684 *
685 * @global stdClass
686 * @global object
0b5a80a1 687 * @param int $courseid
688 * @param string optional type
689 */
690function lesson_reset_gradebook($courseid, $type='') {
646fc290 691 global $CFG, $DB;
0b5a80a1 692
693 $sql = "SELECT l.*, cm.idnumber as cmidnumber, l.course as courseid
646fc290 694 FROM {lesson} l, {course_modules} cm, {modules} m
695 WHERE m.name='lesson' AND m.id=cm.module AND cm.instance=l.id AND l.course=:course";
696 $params = array ("course" => $courseid);
697 if ($lessons = $DB->get_records_sql($sql,$params)) {
0b5a80a1 698 foreach ($lessons as $lesson) {
699 lesson_grade_item_update($lesson, 'reset');
700 }
701 }
702}
703
704/**
72d2982e 705 * Actual implementation of the reset course functionality, delete all the
0b5a80a1 706 * lesson attempts for course $data->courseid.
8cc86111 707 *
708 * @global stdClass
709 * @global object
710 * @param object $data the data submitted from the reset course.
0b5a80a1 711 * @return array status array
712 */
713function lesson_reset_userdata($data) {
646fc290 714 global $CFG, $DB;
0b5a80a1 715
716 $componentstr = get_string('modulenameplural', 'lesson');
717 $status = array();
718
719 if (!empty($data->reset_lesson)) {
720 $lessonssql = "SELECT l.id
646fc290 721 FROM {lesson} l
722 WHERE l.course=:course";
723
724 $params = array ("course" => $data->courseid);
725 $DB->delete_records_select('lesson_timer', "lessonid IN ($lessonssql)", $params);
726 $DB->delete_records_select('lesson_high_scores', "lessonid IN ($lessonssql)", $params);
727 $DB->delete_records_select('lesson_grades', "lessonid IN ($lessonssql)", $params);
728 $DB->delete_records_select('lesson_attempts', "lessonid IN ($lessonssql)", $params);
0b5a80a1 729
730 // remove all grades from gradebook
731 if (empty($data->reset_gradebook_grades)) {
732 lesson_reset_gradebook($data->courseid);
733 }
734
735 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallattempts', 'lesson'), 'error'=>false);
736 }
737
738 /// updating dates - shift may be negative too
739 if ($data->timeshift) {
740 shift_course_mod_dates('lesson', array('available', 'deadline'), $data->timeshift, $data->courseid);
741 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
742 }
743
744 return $status;
745}
746
f432bebf 747/**
748 * Returns all other caps used in module
8cc86111 749 * @return array
f432bebf 750 */
751function lesson_get_extra_capabilities() {
752 return array('moodle/site:accessallgroups');
753}
754
18a2a0cb 755/**
8cc86111 756 * @uses FEATURE_GROUPS
757 * @uses FEATURE_GROUPINGS
758 * @uses FEATURE_GROUPMEMBERSONLY
759 * @uses FEATURE_MOD_INTRO
760 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
761 * @uses FEATURE_GRADE_HAS_GRADE
762 * @uses FEATURE_GRADE_OUTCOMES
18a2a0cb 763 * @param string $feature FEATURE_xx constant for requested feature
8cc86111 764 * @return mixed True if module supports feature, false if not, null if doesn't know
18a2a0cb 765 */
766function lesson_supports($feature) {
767 switch($feature) {
42f103be 768 case FEATURE_GROUPS: return false;
769 case FEATURE_GROUPINGS: return false;
770 case FEATURE_GROUPMEMBERSONLY: return true;
c6949936 771 case FEATURE_MOD_INTRO: return false;
18a2a0cb 772 case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
42f103be 773 case FEATURE_GRADE_HAS_GRADE: return true;
774 case FEATURE_GRADE_OUTCOMES: return true;
c351bb50 775 case FEATURE_BACKUP_MOODLE2: return true;
18a2a0cb 776 default: return null;
777 }
778}
c6949936 779
780/**
792881f0 781 * This function extends the global navigation for the site.
c6949936 782 * It is important to note that you should not rely on PAGE objects within this
783 * body of code as there is no guarantee that during an AJAX request they are
784 * available
785 *
786 * @param navigation_node $navigation The lesson node within the global navigation
787 * @param stdClass $course The course object returned from the DB
788 * @param stdClass $module The module object returned from the DB
792881f0 789 * @param stdClass $cm The course module instance returned from the DB
c6949936 790 */
791function lesson_extend_navigation($navigation, $course, $module, $cm) {
792 /**
793 * This is currently just a stub so that it can be easily expanded upon.
794 * When expanding just remove this comment and the line below and then add
795 * you content.
796 */
797 $navigation->nodetype = navigation_node::NODETYPE_LEAF;
798}
799
800/**
801 * This function extends the settings navigation block for the site.
802 *
803 * It is safe to rely on PAGE here as we will only ever be within the module
804 * context when this is called
805 *
0b29477b
SH
806 * @param settings_navigation $settings
807 * @param navigation_node $lessonnode
c6949936 808 */
0b29477b
SH
809function lesson_extend_settings_navigation($settings, $lessonnode) {
810 global $PAGE, $DB;
0a4abb73 811
c6949936 812 $canedit = has_capability('mod/lesson:edit', $PAGE->cm->context);
813
a6855934 814 $url = new moodle_url('/mod/lesson/view.php', array('id'=>$PAGE->cm->id));
3406acde 815 $lessonnode->add(get_string('preview', 'lesson'), $url);
c6949936 816
817 if ($canedit) {
a6855934 818 $url = new moodle_url('/mod/lesson/edit.php', array('id'=>$PAGE->cm->id));
3406acde 819 $lessonnode->add(get_string('edit', 'lesson'), $url);
c6949936 820 }
821
822 if (has_capability('mod/lesson:manage', $PAGE->cm->context)) {
3406acde 823 $reportsnode = $lessonnode->add(get_string('reports', 'lesson'));
a6855934 824 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportoverview'));
3406acde 825 $reportsnode->add(get_string('overview', 'lesson'), $url);
a6855934 826 $url = new moodle_url('/mod/lesson/report.php', array('id'=>$PAGE->cm->id, 'action'=>'reportdetail'));
3406acde 827 $reportsnode->add(get_string('detailedstats', 'lesson'), $url);
c6949936 828 }
829
830 if ($canedit) {
a6855934 831 $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$PAGE->cm->id));
0b29477b 832 $lessonnode->add(get_string('manualgrading', 'lesson'), $url);
c6949936 833 }
834
57173b8d 835 if ($PAGE->activityrecord->highscores) {
a6855934 836 $url = new moodle_url('/mod/lesson/highscores.php', array('id'=>$PAGE->cm->id));
0b29477b 837 $lessonnode->add(get_string('highscores', 'lesson'), $url);
c6949936 838 }
3406acde 839}
0a4abb73
SH
840
841/**
842 * Get list of available import or export formats
843 *
844 * Copied and modified from lib/questionlib.php
845 *
846 * @param string $type 'import' if import list, otherwise export list assumed
847 * @return array sorted list of import/export formats available
848 */
849function lesson_get_import_export_formats($type) {
850 global $CFG;
851 $fileformats = get_plugin_list("qformat");
852
853 $fileformatname=array();
854 foreach ($fileformats as $fileformat=>$fdir) {
855 $format_file = "$fdir/format.php";
856 if (file_exists($format_file) ) {
857 require_once($format_file);
858 } else {
859 continue;
860 }
861 $classname = "qformat_$fileformat";
862 $format_class = new $classname();
863 if ($type=='import') {
864 $provided = $format_class->provide_import();
865 } else {
866 $provided = $format_class->provide_export();
867 }
868 if ($provided) {
1e7f8ea2 869 //TODO: do NOT rely on [[]] any more!!
0a4abb73
SH
870 $formatname = get_string($fileformat, 'quiz');
871 if ($formatname == "[[$fileformat]]") {
872 $formatname = get_string($fileformat, 'qformat_'.$fileformat);
873 if ($formatname == "[[$fileformat]]") {
874 $formatname = $fileformat; // Just use the raw folder name
875 }
876 }
877 $fileformatnames[$fileformat] = $formatname;
878 }
879 }
880 natcasesort($fileformatnames);
881
882 return $fileformatnames;
883}
884
885/**
886 * Serves the lesson attachments. Implements needed access control ;-)
887 *
888 * @param object $course
64f93798 889 * @param object $cm
0a4abb73
SH
890 * @param object $context
891 * @param string $filearea
892 * @param array $args
893 * @param bool $forcedownload
894 * @return bool false if file not found, does not return if found - justsend the file
895 */
64f93798 896function lesson_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
0a4abb73
SH
897 global $CFG, $DB;
898
64f93798 899 if ($context->contextlevel != CONTEXT_MODULE) {
0a4abb73
SH
900 return false;
901 }
2f67a9b3 902
0a4abb73
SH
903 $fileareas = lesson_get_file_areas();
904 if (!array_key_exists($filearea, $fileareas)) {
905 return false;
906 }
907
64f93798 908 if (!$lesson = $DB->get_record('lesson', array('id'=>$cm->instance))) {
0a4abb73
SH
909 return false;
910 }
911
912 require_course_login($course, true, $cm);
913
64f93798 914 if ($filearea === 'page_contents') {
0a4abb73
SH
915 $pageid = (int)array_shift($args);
916 if (!$page = $DB->get_record('lesson_pages', array('id'=>$pageid))) {
917 return false;
918 }
64f93798 919 $fullpath = "/$context->id/mod_lesson/$filearea/$pageid/".implode('/', $args);
64f93798 920
3d1b7452
PS
921 } else if ($filearea === 'mediafile') {
922 array_shift($args); // ignore itemid - caching only
923 $fullpath = "/$context->id/mod_lesson/$filearea/0/".implode('/', $args);
924
925 } else {
926 return false;
0a4abb73
SH
927 }
928
929 $fs = get_file_storage();
930 if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
931 return false;
932 }
933
934 // finally send the file
935 send_stored_file($file, 0, 0, $forcedownload); // download MUST be forced - security!
936}
937
938/**
939 * Returns an array of file areas
940 * @return array
941 */
942function lesson_get_file_areas() {
64f93798 943 $areas = array();
3d1b7452
PS
944 $areas['page_contents'] = 'Page contents'; //TODO: localize!!!!
945 $areas['mediafile'] = 'Media file'; //TODO: localize!!!!
946
947 return $areas;
0a4abb73
SH
948}
949
950/**
951 * Returns a file_info_stored object for the file being requested here
952 *
953 * @global <type> $CFG
954 * @param file_browse $browser
955 * @param array $areas
956 * @param object $course
957 * @param object $cm
958 * @param object $context
959 * @param string $filearea
960 * @param int $itemid
961 * @param string $filepath
962 * @param string $filename
963 * @return file_info_stored
964 */
965function lesson_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
966 global $CFG;
64f93798
PS
967 if (has_capability('moodle/course:managefiles', $context)) {
968 // no peaking here for students!!
969 return null;
970 }
971
0a4abb73
SH
972 $fs = get_file_storage();
973 $filepath = is_null($filepath) ? '/' : $filepath;
974 $filename = is_null($filename) ? '.' : $filename;
975 $urlbase = $CFG->wwwroot.'/pluginfile.php';
64f93798 976 if (!$storedfile = $fs->get_file($context->id, 'mod_lesson', $filearea, $itemid, $filepath, $filename)) {
0a4abb73
SH
977 return null;
978 }
979 return new file_info_stored($browser, $context, $storedfile, $urlbase, $filearea, $itemid, true, true, false);
980}