Merge branch 'MDL-40054_master' of https://github.com/markn86/moodle
[moodle.git] / mod / lesson / highscores.php
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.
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/>.
18 /**
19  * Provides the interface for viewing and adding high scores
20  *
21  * @package    mod
22  * @subpackage lesson
23  * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  **/
27 /** include required files */
28 require_once('../../config.php');
29 require_once($CFG->dirroot.'/mod/lesson/locallib.php');
31 $id      = required_param('id', PARAM_INT);             // Course Module ID
32 $mode    = optional_param('mode', '', PARAM_ALPHA);
33 $link = optional_param('link', 0, PARAM_INT);
35 $cm = get_coursemodule_from_id('lesson', $id, 0, false, MUST_EXIST);
36 $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
37 $lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST));
39 require_login($course, false, $cm);
41 $url = new moodle_url('/mod/lesson/highscores.php', array('id'=>$id));
42 if ($mode !== '') {
43     $url->param('mode', $mode);
44 }
45 if ($link !== 0) {
46     $url->param('link', $link);
47 }
48 $PAGE->set_url($url);
50 $context = context_module::instance($cm->id);
52 switch ($mode) {
53     case 'add':
54         // Ensure that we came from view.php
55         if (!confirm_sesskey() or !data_submitted()) {
56             print_error('invalidformdata');
57         }
58         break;
60     case 'save':
61         if (confirm_sesskey() and $form = data_submitted($CFG->wwwroot.'/mod/lesson/view.php')) {
62             $name = trim(optional_param('name', '', PARAM_CLEAN));
64             // Make sure it is not empty
65             if (empty($name)) {
66                 $lesson->add_message(get_string('missingname', 'lesson'));
67                 $mode = 'add';
68                 break;
69             }
70             // Check for censored words
71             $filterwords = explode(',', get_string('censorbadwords'));
72             foreach ($filterwords as $filterword) {
73                 if (strstr($name, $filterword)) {
74                     $lesson->add_message(get_string('namereject', 'lesson'));
75                     $mode = 'add';
76                     break;
77                 }
78             }
79             // Bad word was found
80             if ($mode == 'add') {
81                 break;
82             }
83             $params = array ("lessonid" => $lesson->id, "userid" => $USER->id);
84             if (!$grades = $DB->get_records_select('lesson_grades', "lessonid = :lessonid", $params, 'completed')) {
85                 print_error('cannotfindfirstgrade', 'lesson');
86             }
88             if (!$newgrade = $DB->get_record_sql("SELECT *
89                                                FROM {lesson_grades}
90                                               WHERE lessonid = :lessonid
91                                                 AND userid = :userid
92                                            ORDER BY completed DESC", $params, true)) {
93                 print_error('cannotfindnewestgrade', 'lesson');
94             }
96             // Check for multiple submissions
97             if ($DB->record_exists('lesson_high_scores', array('gradeid' => $newgrade->id))) {
98                 print_error('onpostperpage', 'lesson');
99             }
101             // Find out if we need to delete any records
102             if ($highscores = $DB->get_records_sql("SELECT h.*, g.grade
103                                                  FROM {lesson_grades} g, {lesson_high_scores} h
104                                                 WHERE h.gradeid = g.id
105                                                 AND h.lessonid = :lessonid
106                                                 ORDER BY g.grade DESC", $params)) {
107                 // Only count unique scores in our total for max high scores
108                 $uniquescores = array();
109                 foreach ($highscores as $highscore) {
110                     $uniquescores[$highscore->grade] = 1;
111                 }
112                 if (count($uniquescores) >= $lesson->maxhighscores) {
113                     // Top scores list is full, might need to delete a score
114                     $flag = true;
115                     // See if the new score is already listed in the top scores list
116                     // if it is listed, then dont need to delete any records
117                     foreach ($highscores as $highscore) {
118                         if ($newgrade->grade == $highscore->grade) {
119                             $flag = false;
120                         }
121                     }
122                     if ($flag) {
123                         // Pushing out the lowest score (could be multiple records)
124                         $lowscore = 0;
125                         foreach ($highscores as $highscore) {
126                             if (empty($lowscore) or $lowscore > $highscore->grade) {
127                                 $lowscore = $highscore->grade;
128                             }
129                         }
130                         // Now, delete all high scores with the low score
131                         foreach ($highscores as $highscore) {
132                             if ($highscore->grade == $lowscore) {
133                                 $DB->delete_records('lesson_high_scores', array('id' => $highscore->id));
134                             }
135                         }
136                     }
137                 }
138             }
140             $newhighscore = new stdClass;
141             $newhighscore->lessonid = $lesson->id;
142             $newhighscore->userid = $USER->id;
143             $newhighscore->gradeid = $newgrade->id;
144             $newhighscore->nickname = $name;
146             $newhighscore->id = $DB->insert_record('lesson_high_scores', $newhighscore);
148             // Trigger highscore updated event.
149             $event = \mod_lesson\event\highscore_added::create(array(
150                 'objectid' => $newhighscore->id,
151                 'context' => $context,
152                 'courseid' => $course->id,
153             ));
154             $event->trigger();
156             $lesson->add_message(get_string('postsuccess', 'lesson'), 'notifysuccess');
157             redirect("$CFG->wwwroot/mod/lesson/highscores.php?id=$cm->id&amp;link=1");
158         } else {
159             print_error('invalidformdata');
160         }
161         break;
164 // Trigger highscore viewed event.
165 $event = \mod_lesson\event\highscores_viewed::create(array(
166     'objectid' => $lesson->properties()->id,
167     'context' => $context,
168     'courseid' => $course->id
169 ));
170 $event->trigger();
172 $lessonoutput = $PAGE->get_renderer('mod_lesson');
173 echo $lessonoutput->header($lesson, $cm, 'highscores', false, null, get_string('viewhighscores', 'lesson'));
175 switch ($mode) {
176     case 'add':
177         echo $lessonoutput->add_highscores_form($lesson);
178         break;
179     default:
180         $params = array ("lessonid" => $lesson->id);
181         if (!$grades = $DB->get_records_select("lesson_grades", "lessonid = :lessonid", $params, "completed")) {
182             $grades = array();
183         }
185         echo $OUTPUT->heading(get_string("topscorestitle", "lesson", $lesson->maxhighscores), 4);
187         if (!$highscores = $DB->get_records_select("lesson_high_scores", "lessonid = :lessonid", $params)) {
188             echo $OUTPUT->heading(get_string("nohighscores", "lesson"), 3);
189         } else {
190             foreach ($highscores as $highscore) {
191                 $grade = $grades[$highscore->gradeid]->grade;
192                 $topscores[$grade][] = $highscore->nickname;
193             }
194             krsort($topscores);
196             $table = new html_table();
197             $table->align = array('center', 'left', 'right');
198             $table->wrap = array();
199             $table->width = "30%";
200             $table->cellspacing = '10px';
201             $table->size = array('*', '*', '*');
203             $table->head = array(get_string("rank", "lesson"), get_string('name'), get_string("scores", "lesson"));
205             $printed = 0;
206             while (true) {
207                 $temp = current($topscores);
208                 $score = key($topscores);
209                 $rank = $printed + 1;
210                 sort($temp);
211                 foreach ($temp as $student) {
212                     $table->data[] = array($rank, $student, $score.'%');
213                 }
214                 $printed++;
215                 if (!next($topscores) || !($printed < $lesson->maxhighscores)) {
216                     break;
217                 }
218             }
219             echo html_writer::table($table);
220         }
222         if (!has_capability('mod/lesson:manage', $context)) {  // teachers don't need the links
223             echo $OUTPUT->box_start('mdl-align');
224             echo $OUTPUT->box_start('lessonbutton standardbutton');
225             if ($link) {
226                 echo html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), get_string("returntocourse", "lesson"));
227             } else {
228                 echo html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), get_string("cancel", "lesson")). ' ';
229                 echo html_writer::link(new moodle_url('/mod/lesson/view.php', array('id'=>$cm->id, 'viewed'=>'1')), get_string("startlesson", "lesson"));
230             }
231             echo $OUTPUT->box_end();
232             echo $OUTPUT->box_end();
233         }
234         break;
237 echo $lessonoutput->footer();