Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 78cc7bee62
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 400 lines (344 sloc) 17.241 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* Provides the interface for grading essay questions
*
* @package mod
* @subpackage lesson
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
**/

require_once('../../config.php');
require_once($CFG->dirroot.'/mod/lesson/locallib.php');
require_once($CFG->dirroot.'/mod/lesson/essay_form.php');
require_once($CFG->libdir.'/eventslib.php');

$id = required_param('id', PARAM_INT); // Course Module ID
$mode = optional_param('mode', 'display', PARAM_ALPHA);

$cm = get_coursemodule_from_id('lesson', $id, 0, false, MUST_EXIST);;
$course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
$lesson = new lesson($DB->get_record('lesson', array('id' => $cm->instance), '*', MUST_EXIST));

require_login($course, false, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_capability('mod/lesson:edit', $context);

$url = new moodle_url('/mod/lesson/essay.php', array('id'=>$id));
if ($mode !== 'display') {
    $url->param('mode', $mode);
}
$PAGE->set_url($url);

/// Handle any preprocessing before header is printed - based on $mode
switch ($mode) {
    case 'grade':
        // Grading form - get the necessary data
        require_sesskey();

        $attemptid = required_param('attemptid', PARAM_INT);

        if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $attemptid))) {
            print_error('cannotfindattempt', 'lesson');
        }
        $page = $lesson->load_page($attempt->pageid);
        if (!$user = $DB->get_record('user', array('id' => $attempt->userid))) {
            print_error('cannotfinduser', 'lesson');
        }
        if (!$answer = $DB->get_record('lesson_answers', array('lessonid' => $lesson->id, 'pageid' => $page->id))) {
            print_error('cannotfindanswer', 'lesson');
        }
        break;

    case 'update':
        require_sesskey();
        $mform = new essay_grading_form();
        if ($form = $mform->get_data()) {

            if (optional_param('cancel', false, PARAM_RAW)) {
                redirect("$CFG->wwwroot/mod/lesson/essay.php?id=$cm->id");
            }

            $attemptid = required_param('attemptid', PARAM_INT);
            $score = optional_param('score', 0, PARAM_INT);

            if (!$attempt = $DB->get_record('lesson_attempts', array('id' => $attemptid))) {
                print_error('cannotfindattempt', 'lesson');
            }
            if (!$grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1)) {
                print_error('cannotfindgrade', 'lesson');
            }

            $essayinfo = new stdClass;
            $essayinfo = unserialize($attempt->useranswer);

            $essayinfo->graded = 1;
            $essayinfo->score = $score;
            $essayinfo->response = clean_param($form->response, PARAM_RAW);
            $essayinfo->sent = 0;
            if (!$lesson->custom && $essayinfo->score == 1) {
                $attempt->correct = 1;
            } else {
                $attempt->correct = 0;
            }

            $attempt->useranswer = serialize($essayinfo);

            $DB->update_record('lesson_attempts', $attempt);

            // Get grade information
            $grade = current($grades);
            $gradeinfo = lesson_grade($lesson, $attempt->retry, $attempt->userid);

            // Set and update
            $updategrade = new stdClass();
            $updategrade->id = $grade->id;
            $updategrade->grade = $gradeinfo->grade;
            $DB->update_record('lesson_grades', $updategrade);
            // Log it
            add_to_log($course->id, 'lesson', 'update grade', "essay.php?id=$cm->id", $lesson->name, $cm->id);

            $lesson->add_message(get_string('changessaved'), 'notifysuccess');

            // update central gradebook
            lesson_update_grades($lesson, $grade->userid);

            redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
        } else {
            print_error('invalidformdata');
        }
        break;
    case 'email':
        // Sending an email(s) to a single user or all
        require_sesskey();

        // Get our users (could be singular)
        if ($userid = optional_param('userid', 0, PARAM_INT)) {
            $queryadd = " AND userid = ?";
            if (! $users = $DB->get_records('user', array('id' => $userid))) {
                print_error('cannotfinduser', 'lesson');
            }
        } else {
            $queryadd = '';
            $params = array ("lessonid" => $lesson->id);
            // Need to use inner view to avoid distinct + text
            if (!$users = $DB->get_records_sql("
SELECT u.*
FROM {user} u
JOIN (
SELECT DISTINCT u.id
FROM {user} u,
{lesson_attempts} a
WHERE a.lessonid = :lessonid and
u.id = a.userid) ui ON (u.id = ui.id)
ORDER BY u.lastname", $params)) {
                print_error('cannotfinduser', 'lesson');
            }
        }

        $pages = $lesson->load_all_pages();
        foreach ($pages as $key=>$page) {
            if ($page->qtype !== LESSON_PAGE_ESSAY) {
                unset($pages[$key]);
            }
        }

        // Get only the attempts that are in response to essay questions
        list($usql, $params) = $DB->get_in_or_equal(array_keys($pages));
        if (!empty($queryadd)) {
            $params[] = $userid;
        }
        if (!$attempts = $DB->get_records_select('lesson_attempts', "pageid $usql".$queryadd, $params)) {
            print_error('nooneansweredthisquestion', 'lesson');
        }
        // Get the answers
        list($answerUsql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
        array_unshift($parameters, $lesson->id);
        if (!$answers = $DB->get_records_select('lesson_answers', "lessonid = ? AND pageid $answerUsql", $parameters, '', 'pageid, score')) {
            print_error('cannotfindanswer', 'lesson');
        }
        $options = new stdClass;
        $options->noclean = true;

        foreach ($attempts as $attempt) {
            $essayinfo = unserialize($attempt->useranswer);
            if ($essayinfo->graded && !$essayinfo->sent) {
                // Holds values for the essayemailsubject string for the email message
                $a = new stdClass;

                // Set the grade
                $grades = $DB->get_records('lesson_grades', array("lessonid"=>$lesson->id, "userid"=>$attempt->userid), 'completed', '*', $attempt->retry, 1);
                $grade = current($grades);
                $a->newgrade = $grade->grade;

                // Set the points
                if ($lesson->custom) {
                    $a->earned = $essayinfo->score;
                    $a->outof = $answers[$attempt->pageid]->score;
                } else {
                    $a->earned = $essayinfo->score;
                    $a->outof = 1;
                }

                // Set rest of the message values
                $currentpage = $lesson->load_page($attempt->pageid);
                $a->question = format_text($currentpage->contents, $currentpage->contentsformat, $options);
                $a->response = s($essayinfo->answer);
                $a->comment = s($essayinfo->response);

                // Fetch message HTML and plain text formats
                $message = get_string('essayemailmessage2', 'lesson', $a);
                $plaintext = format_text_email($message, FORMAT_HTML);

                // Subject
                $subject = get_string('essayemailsubject', 'lesson', format_string($pages[$attempt->pageid]->title,true));

                $eventdata = new stdClass();
                $eventdata->modulename = 'lesson';
                $eventdata->userfrom = $USER;
                $eventdata->userto = $users[$attempt->userid];
                $eventdata->subject = $subject;
                $eventdata->fullmessage = $plaintext;
                $eventdata->fullmessageformat = FORMAT_PLAIN;
                $eventdata->fullmessagehtml = $message;
                $eventdata->smallmessage = '';

                // Required for messaging framework
                $eventdata->component = 'mod_lesson';
                $eventdata->name = 'graded_essay';

                message_send($eventdata);
                $essayinfo->sent = 1;
                $attempt->useranswer = serialize($essayinfo);
                $DB->update_record('lesson_attempts', $attempt);
                // Log it
                add_to_log($course->id, 'lesson', 'update email essay grade', "essay.php?id=$cm->id", format_string($pages[$attempt->pageid]->title,true).': '.fullname($users[$attempt->userid]), $cm->id);
            }
        }
        $lesson->add_message(get_string('emailsuccess', 'lesson'), 'notifysuccess');
        redirect(new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id)));
        break;
    case 'display': // Default view - get the necessary data
    default:
        // Get lesson pages that are essay
        $pages = $lesson->load_all_pages();
        foreach ($pages as $key=>$page) {
            if ($page->qtype !== LESSON_PAGE_ESSAY) {
                unset($pages[$key]);
            }
        }
        if (count($pages) > 0) {
            $params = array ("lessonid" => $lesson->id, "qtype" => LESSON_PAGE_ESSAY);
            // Get only the attempts that are in response to essay questions
            list($usql, $parameters) = $DB->get_in_or_equal(array_keys($pages));
            if ($essayattempts = $DB->get_records_select('lesson_attempts', 'pageid '.$usql, $parameters)) {
                // Get all the users who have taken this lesson, order by their last name
                $ufields = user_picture::fields('u');
                if (!empty($cm->groupingid)) {
                    $params["groupinid"] = $cm->groupingid;
                    $sql = "SELECT DISTINCT $ufields
FROM {lesson_attempts} a
INNER JOIN {user} u ON u.id = a.userid
INNER JOIN {groups_members} gm ON gm.userid = u.id
INNER JOIN {groupings_groups} gg ON gm.groupid = :groupinid
WHERE a.lessonid = :lessonid
ORDER BY u.lastname";
                } else {
                    $sql = "SELECT DISTINCT $ufields
FROM {user} u,
{lesson_attempts} a
WHERE a.lessonid = :lessonid and
u.id = a.userid
ORDER BY u.lastname";
                }
                if (!$users = $DB->get_records_sql($sql, $params)) {
                    $mode = 'none'; // not displaying anything
                    $lesson->add_message(get_string('noonehasanswered', 'lesson'));
                }
            } else {
                $mode = 'none'; // not displaying anything
                $lesson->add_message(get_string('noonehasanswered', 'lesson'));
            }
        } else {
            $mode = 'none'; // not displaying anything
            $lesson->add_message(get_string('noessayquestionsfound', 'lesson'));
        }
        break;
}
// Log it
add_to_log($course->id, 'lesson', 'view grade', "essay.php?id=$cm->id", get_string('manualgrading', 'lesson'), $cm->id);

$lessonoutput = $PAGE->get_renderer('mod_lesson');
echo $lessonoutput->header($lesson, $cm, 'essay');

switch ($mode) {
    case 'display':
        // Expects $user, $essayattempts and $pages to be set already

        // Group all the essays by userid
        $studentessays = array();
        foreach ($essayattempts as $essay) {
            // Not very nice :) but basically
            // this organizes the essays so we know how many
            // times a student answered an essay per try and per page
            $studentessays[$essay->userid][$essay->pageid][$essay->retry][] = $essay;
        }

        // Setup table
        $table = new html_table();
        $table->head = array(get_string('name'), get_string('essays', 'lesson'), get_string('email', 'lesson'));
        $table->attributes['class'] = 'standardtable generaltable';
        $table->align = array('left', 'left', 'left');
        $table->wrap = array('nowrap', 'nowrap', '');

        // Cycle through all the students
        foreach (array_keys($studentessays) as $userid) {
            $studentname = fullname($users[$userid], true);
            $essaylinks = array();

            // Number of attempts on the lesson
            $attempts = $DB->count_records('lesson_grades', array('userid'=>$userid, 'lessonid'=>$lesson->id));

            // Go through each essay page
            foreach ($studentessays[$userid] as $page => $tries) {
                $count = 0;

                // Go through each attempt per page
                foreach($tries as $try) {
                    if ($count == $attempts) {
                        break; // Stop displaying essays (attempt not completed)
                    }
                    $count++;

                    // Make sure they didn't answer it more than the max number of attmepts
                    if (count($try) > $lesson->maxattempts) {
                        $essay = $try[$lesson->maxattempts-1];
                    } else {
                        $essay = end($try);
                    }

                    // Start processing the attempt
                    $essayinfo = unserialize($essay->useranswer);

                    // link for each essay
                    $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'grade','attemptid'=>$essay->id,'sesskey'=>sesskey()));
                    $attributes = array();
                    // Different colors for all the states of an essay (graded, if sent, not graded)
                    if (!$essayinfo->graded) {
                        $attributes['class'] = "graded";
                    } elseif (!$essayinfo->sent) {
                        $attributes['class'] = "sent";
                    } else {
                        $attributes['class'] = "ungraded";
                    }
                    $essaylinks[] = html_writer::link($url, userdate($essay->timeseen, get_string('strftimedatetime')).' '.format_string($pages[$essay->pageid]->title,true), $attributes);
                }
            }
            // email link for this user
            $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','userid'=>$userid,'sesskey'=>sesskey()));
            $emaillink = html_writer::link($url, get_string('emailgradedessays', 'lesson'));

            $table->data[] = array($OUTPUT->user_picture($users[$userid], array('courseid'=>$course->id)).$studentname, implode("<br />", $essaylinks), $emaillink);
        }

        // email link for all users
        $url = new moodle_url('/mod/lesson/essay.php', array('id'=>$cm->id,'mode'=>'email','sesskey'=>sesskey()));
        $emailalllink = html_writer::link($url, get_string('emailallgradedessays', 'lesson'));

        $table->data[] = array(' ', ' ', $emailalllink);

        echo html_writer::table($table);
        break;
    case 'grade':
        // Grading form
        // Expects the following to be set: $attemptid, $answer, $user, $page, $attempt


        $essayinfo = unserialize($attempt->useranswer);
        $options = array();
        if ($lesson->custom) {
            $i = $answer->score;
            while ($i >= 0) {
                $options[$i] = (string)$i;
                $i--;
            }
        } else {
            $options[0] = get_string('nocredit', 'lesson');
            $options[1] = get_string('credit', 'lesson');
        }
        $mform = new essay_grading_form(null, array('scoreoptions'=>$options, 'user'=>$user));

        $data = new stdClass;
        $data->id = $cm->id;
        $data->attemptid = $attemptid;
        $data->score = $essayinfo->score;
        $data->studentanswer = format_string($essayinfo->answer, FORMAT_MOODLE);
        $data->response = $essayinfo->response;
        $mform->set_data($data);

        $mform->display();
        break;
}

echo $OUTPUT->footer();
Something went wrong with that request. Please try again.