Merge branch 'MDL-40551_master' of https://github.com/totara/openbadges
[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             $DB->insert_record('lesson_high_scores', $newhighscore);
148             // Log it
149             add_to_log($course->id, 'lesson', 'update highscores', "highscores.php?id=$cm->id", $name, $cm->id);
151             $lesson->add_message(get_string('postsuccess', 'lesson'), 'notifysuccess');
152             redirect("$CFG->wwwroot/mod/lesson/highscores.php?id=$cm->id&amp;link=1");
153         } else {
154             print_error('invalidformdata');
155         }
156         break;
159 // Log it
160 add_to_log($course->id, 'lesson', 'view highscores', "highscores.php?id=$cm->id", $lesson->name, $cm->id);
162 $lessonoutput = $PAGE->get_renderer('mod_lesson');
163 echo $lessonoutput->header($lesson, $cm, 'highscores', false, null, get_string('viewhighscores', 'lesson'));
165 switch ($mode) {
166     case 'add':
167         echo $lessonoutput->add_highscores_form($lesson);
168         break;
169     default:
170         $params = array ("lessonid" => $lesson->id);
171         if (!$grades = $DB->get_records_select("lesson_grades", "lessonid = :lessonid", $params, "completed")) {
172             $grades = array();
173         }
175         echo $OUTPUT->heading(get_string("topscorestitle", "lesson", $lesson->maxhighscores), 4);
177         if (!$highscores = $DB->get_records_select("lesson_high_scores", "lessonid = :lessonid", $params)) {
178             echo $OUTPUT->heading(get_string("nohighscores", "lesson"), 3);
179         } else {
180             foreach ($highscores as $highscore) {
181                 $grade = $grades[$highscore->gradeid]->grade;
182                 $topscores[$grade][] = $highscore->nickname;
183             }
184             krsort($topscores);
186             $table = new html_table();
187             $table->align = array('center', 'left', 'right');
188             $table->wrap = array();
189             $table->width = "30%";
190             $table->cellspacing = '10px';
191             $table->size = array('*', '*', '*');
193             $table->head = array(get_string("rank", "lesson"), get_string('name'), get_string("scores", "lesson"));
195             $printed = 0;
196             while (true) {
197                 $temp = current($topscores);
198                 $score = key($topscores);
199                 $rank = $printed + 1;
200                 sort($temp);
201                 foreach ($temp as $student) {
202                     $table->data[] = array($rank, $student, $score.'%');
203                 }
204                 $printed++;
205                 if (!next($topscores) || !($printed < $lesson->maxhighscores)) {
206                     break;
207                 }
208             }
209             echo html_writer::table($table);
210         }
212         if (!has_capability('mod/lesson:manage', $context)) {  // teachers don't need the links
213             echo $OUTPUT->box_start('mdl-align');
214             echo $OUTPUT->box_start('lessonbutton standardbutton');
215             if ($link) {
216                 echo html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), get_string("returntocourse", "lesson"));
217             } else {
218                 echo html_writer::link(new moodle_url('/course/view.php', array('id'=>$course->id)), get_string("cancel", "lesson")). ' ';
219                 echo html_writer::link(new moodle_url('/mod/lesson/view.php', array('id'=>$cm->id, 'viewed'=>'1')), get_string("startlesson", "lesson"));
220             }
221             echo $OUTPUT->box_end();
222             echo $OUTPUT->box_end();
223         }
224         break;
227 echo $lessonoutput->footer();