PageRenderTime 116ms CodeModel.GetById 40ms app.highlight 65ms RepoModel.GetById 1ms app.codeStats 0ms

/mod/quiz/locallib.php

https://bitbucket.org/ngmares/moodle
PHP | 1565 lines | 893 code | 196 blank | 476 comment | 148 complexity | 6d3ac39731ff659fb268ea585ff2e3e4 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2// This file is part of Moodle - http://moodle.org/
   3//
   4// Moodle is free software: you can redistribute it and/or modify
   5// it under the terms of the GNU General Public License as published by
   6// the Free Software Foundation, either version 3 of the License, or
   7// (at your option) any later version.
   8//
   9// Moodle is distributed in the hope that it will be useful,
  10// but WITHOUT ANY WARRANTY; without even the implied warranty of
  11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12// GNU General Public License for more details.
  13//
  14// You should have received a copy of the GNU General Public License
  15// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16
  17/**
  18 * Library of functions used by the quiz module.
  19 *
  20 * This contains functions that are called from within the quiz module only
  21 * Functions that are also called by core Moodle are in {@link lib.php}
  22 * This script also loads the code in {@link questionlib.php} which holds
  23 * the module-indpendent code for handling questions and which in turn
  24 * initialises all the questiontype classes.
  25 *
  26 * @package    mod
  27 * @subpackage quiz
  28 * @copyright  1999 onwards Martin Dougiamas and others {@link http://moodle.com}
  29 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  30 */
  31
  32
  33defined('MOODLE_INTERNAL') || die();
  34
  35require_once($CFG->dirroot . '/mod/quiz/lib.php');
  36require_once($CFG->dirroot . '/mod/quiz/accessmanager.php');
  37require_once($CFG->dirroot . '/mod/quiz/accessmanager_form.php');
  38require_once($CFG->dirroot . '/mod/quiz/renderer.php');
  39require_once($CFG->dirroot . '/mod/quiz/attemptlib.php');
  40require_once($CFG->dirroot . '/question/editlib.php');
  41require_once($CFG->libdir  . '/eventslib.php');
  42require_once($CFG->libdir . '/filelib.php');
  43
  44
  45/**
  46 * @var int We show the countdown timer if there is less than this amount of time left before the
  47 * the quiz close date. (1 hour)
  48 */
  49define('QUIZ_SHOW_TIME_BEFORE_DEADLINE', '3600');
  50
  51/**
  52 * @var int If there are fewer than this many seconds left when the student submits
  53 * a page of the quiz, then do not take them to the next page of the quiz. Instead
  54 * close the quiz immediately.
  55 */
  56define('QUIZ_MIN_TIME_TO_CONTINUE', '2');
  57
  58
  59// Functions related to attempts ///////////////////////////////////////////////
  60
  61/**
  62 * Creates an object to represent a new attempt at a quiz
  63 *
  64 * Creates an attempt object to represent an attempt at the quiz by the current
  65 * user starting at the current time. The ->id field is not set. The object is
  66 * NOT written to the database.
  67 *
  68 * @param object $quiz the quiz to create an attempt for.
  69 * @param int $attemptnumber the sequence number for the attempt.
  70 * @param object $lastattempt the previous attempt by this user, if any. Only needed
  71 *         if $attemptnumber > 1 and $quiz->attemptonlast is true.
  72 * @param int $timenow the time the attempt was started at.
  73 * @param bool $ispreview whether this new attempt is a preview.
  74 *
  75 * @return object the newly created attempt object.
  76 */
  77function quiz_create_attempt($quiz, $attemptnumber, $lastattempt, $timenow, $ispreview = false) {
  78    global $USER;
  79
  80    if ($quiz->sumgrades < 0.000005 && $quiz->grade > 0.000005) {
  81        throw new moodle_exception('cannotstartgradesmismatch', 'quiz',
  82                new moodle_url('/mod/quiz/view.php', array('q' => $quiz->id)),
  83                    array('grade' => quiz_format_grade($quiz, $quiz->grade)));
  84    }
  85
  86    if ($attemptnumber == 1 || !$quiz->attemptonlast) {
  87        // We are not building on last attempt so create a new attempt.
  88        $attempt = new stdClass();
  89        $attempt->quiz = $quiz->id;
  90        $attempt->userid = $USER->id;
  91        $attempt->preview = 0;
  92        $attempt->layout = quiz_clean_layout($quiz->questions, true);
  93        if ($quiz->shufflequestions) {
  94            $attempt->layout = quiz_repaginate($attempt->layout, $quiz->questionsperpage, true);
  95        }
  96    } else {
  97        // Build on last attempt.
  98        if (empty($lastattempt)) {
  99            print_error('cannotfindprevattempt', 'quiz');
 100        }
 101        $attempt = $lastattempt;
 102    }
 103
 104    $attempt->attempt = $attemptnumber;
 105    $attempt->timestart = $timenow;
 106    $attempt->timefinish = 0;
 107    $attempt->timemodified = $timenow;
 108    $attempt->state = quiz_attempt::IN_PROGRESS;
 109
 110    // If this is a preview, mark it as such.
 111    if ($ispreview) {
 112        $attempt->preview = 1;
 113    }
 114
 115    return $attempt;
 116}
 117
 118/**
 119 * Returns an unfinished attempt (if there is one) for the given
 120 * user on the given quiz. This function does not return preview attempts.
 121 *
 122 * @param int $quizid the id of the quiz.
 123 * @param int $userid the id of the user.
 124 *
 125 * @return mixed the unfinished attempt if there is one, false if not.
 126 */
 127function quiz_get_user_attempt_unfinished($quizid, $userid) {
 128    $attempts = quiz_get_user_attempts($quizid, $userid, 'unfinished', true);
 129    if ($attempts) {
 130        return array_shift($attempts);
 131    } else {
 132        return false;
 133    }
 134}
 135
 136/**
 137 * Delete a quiz attempt.
 138 * @param mixed $attempt an integer attempt id or an attempt object
 139 *      (row of the quiz_attempts table).
 140 * @param object $quiz the quiz object.
 141 */
 142function quiz_delete_attempt($attempt, $quiz) {
 143    global $DB;
 144    if (is_numeric($attempt)) {
 145        if (!$attempt = $DB->get_record('quiz_attempts', array('id' => $attempt))) {
 146            return;
 147        }
 148    }
 149
 150    if ($attempt->quiz != $quiz->id) {
 151        debugging("Trying to delete attempt $attempt->id which belongs to quiz $attempt->quiz " .
 152                "but was passed quiz $quiz->id.");
 153        return;
 154    }
 155
 156    question_engine::delete_questions_usage_by_activity($attempt->uniqueid);
 157    $DB->delete_records('quiz_attempts', array('id' => $attempt->id));
 158
 159    // Search quiz_attempts for other instances by this user.
 160    // If none, then delete record for this quiz, this user from quiz_grades
 161    // else recalculate best grade.
 162    $userid = $attempt->userid;
 163    if (!$DB->record_exists('quiz_attempts', array('userid' => $userid, 'quiz' => $quiz->id))) {
 164        $DB->delete_records('quiz_grades', array('userid' => $userid, 'quiz' => $quiz->id));
 165    } else {
 166        quiz_save_best_grade($quiz, $userid);
 167    }
 168
 169    quiz_update_grades($quiz, $userid);
 170}
 171
 172/**
 173 * Delete all the preview attempts at a quiz, or possibly all the attempts belonging
 174 * to one user.
 175 * @param object $quiz the quiz object.
 176 * @param int $userid (optional) if given, only delete the previews belonging to this user.
 177 */
 178function quiz_delete_previews($quiz, $userid = null) {
 179    global $DB;
 180    $conditions = array('quiz' => $quiz->id, 'preview' => 1);
 181    if (!empty($userid)) {
 182        $conditions['userid'] = $userid;
 183    }
 184    $previewattempts = $DB->get_records('quiz_attempts', $conditions);
 185    foreach ($previewattempts as $attempt) {
 186        quiz_delete_attempt($attempt, $quiz);
 187    }
 188}
 189
 190/**
 191 * @param int $quizid The quiz id.
 192 * @return bool whether this quiz has any (non-preview) attempts.
 193 */
 194function quiz_has_attempts($quizid) {
 195    global $DB;
 196    return $DB->record_exists('quiz_attempts', array('quiz' => $quizid, 'preview' => 0));
 197}
 198
 199// Functions to do with quiz layout and pages //////////////////////////////////
 200
 201/**
 202 * Returns a comma separated list of question ids for the quiz
 203 *
 204 * @param string $layout The string representing the quiz layout. Each page is
 205 *      represented as a comma separated list of question ids and 0 indicating
 206 *      page breaks. So 5,2,0,3,0 means questions 5 and 2 on page 1 and question
 207 *      3 on page 2
 208 * @return string comma separated list of question ids, without page breaks.
 209 */
 210function quiz_questions_in_quiz($layout) {
 211    $questions = str_replace(',0', '', quiz_clean_layout($layout, true));
 212    if ($questions === '0') {
 213        return '';
 214    } else {
 215        return $questions;
 216    }
 217}
 218
 219/**
 220 * Returns the number of pages in a quiz layout
 221 *
 222 * @param string $layout The string representing the quiz layout. Always ends in ,0
 223 * @return int The number of pages in the quiz.
 224 */
 225function quiz_number_of_pages($layout) {
 226    return substr_count(',' . $layout, ',0');
 227}
 228
 229/**
 230 * Returns the number of questions in the quiz layout
 231 *
 232 * @param string $layout the string representing the quiz layout.
 233 * @return int The number of questions in the quiz.
 234 */
 235function quiz_number_of_questions_in_quiz($layout) {
 236    $layout = quiz_questions_in_quiz(quiz_clean_layout($layout));
 237    $count = substr_count($layout, ',');
 238    if ($layout !== '') {
 239        $count++;
 240    }
 241    return $count;
 242}
 243
 244/**
 245 * Re-paginates the quiz layout
 246 *
 247 * @param string $layout  The string representing the quiz layout. If there is
 248 *      if there is any doubt about the quality of the input data, call
 249 *      quiz_clean_layout before you call this function.
 250 * @param int $perpage The number of questions per page
 251 * @param bool $shuffle Should the questions be reordered randomly?
 252 * @return string the new layout string
 253 */
 254function quiz_repaginate($layout, $perpage, $shuffle = false) {
 255    $questions = quiz_questions_in_quiz($layout);
 256    if (!$questions) {
 257        return '0';
 258    }
 259
 260    $questions = explode(',', quiz_questions_in_quiz($layout));
 261    if ($shuffle) {
 262        shuffle($questions);
 263    }
 264
 265    $onthispage = 0;
 266    $layout = array();
 267    foreach ($questions as $question) {
 268        if ($perpage and $onthispage >= $perpage) {
 269            $layout[] = 0;
 270            $onthispage = 0;
 271        }
 272        $layout[] = $question;
 273        $onthispage += 1;
 274    }
 275
 276    $layout[] = 0;
 277    return implode(',', $layout);
 278}
 279
 280// Functions to do with quiz grades ////////////////////////////////////////////
 281
 282/**
 283 * Creates an array of maximum grades for a quiz
 284 *
 285 * The grades are extracted from the quiz_question_instances table.
 286 * @param object $quiz The quiz settings.
 287 * @return array of grades indexed by question id. These are the maximum
 288 *      possible grades that students can achieve for each of the questions.
 289 */
 290function quiz_get_all_question_grades($quiz) {
 291    global $CFG, $DB;
 292
 293    $questionlist = quiz_questions_in_quiz($quiz->questions);
 294    if (empty($questionlist)) {
 295        return array();
 296    }
 297
 298    $params = array($quiz->id);
 299    $wheresql = '';
 300    if (!is_null($questionlist)) {
 301        list($usql, $question_params) = $DB->get_in_or_equal(explode(',', $questionlist));
 302        $wheresql = " AND question $usql ";
 303        $params = array_merge($params, $question_params);
 304    }
 305
 306    $instances = $DB->get_records_sql("SELECT question, grade, id
 307                                    FROM {quiz_question_instances}
 308                                    WHERE quiz = ? $wheresql", $params);
 309
 310    $list = explode(",", $questionlist);
 311    $grades = array();
 312
 313    foreach ($list as $qid) {
 314        if (isset($instances[$qid])) {
 315            $grades[$qid] = $instances[$qid]->grade;
 316        } else {
 317            $grades[$qid] = 1;
 318        }
 319    }
 320    return $grades;
 321}
 322
 323/**
 324 * Convert the raw grade stored in $attempt into a grade out of the maximum
 325 * grade for this quiz.
 326 *
 327 * @param float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
 328 * @param object $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
 329 * @param bool|string $format whether to format the results for display
 330 *      or 'question' to format a question grade (different number of decimal places.
 331 * @return float|string the rescaled grade, or null/the lang string 'notyetgraded'
 332 *      if the $grade is null.
 333 */
 334function quiz_rescale_grade($rawgrade, $quiz, $format = true) {
 335    if (is_null($rawgrade)) {
 336        $grade = null;
 337    } else if ($quiz->sumgrades >= 0.000005) {
 338        $grade = $rawgrade * $quiz->grade / $quiz->sumgrades;
 339    } else {
 340        $grade = 0;
 341    }
 342    if ($format === 'question') {
 343        $grade = quiz_format_question_grade($quiz, $grade);
 344    } else if ($format) {
 345        $grade = quiz_format_grade($quiz, $grade);
 346    }
 347    return $grade;
 348}
 349
 350/**
 351 * Get the feedback text that should be show to a student who
 352 * got this grade on this quiz. The feedback is processed ready for diplay.
 353 *
 354 * @param float $grade a grade on this quiz.
 355 * @param object $quiz the quiz settings.
 356 * @param object $context the quiz context.
 357 * @return string the comment that corresponds to this grade (empty string if there is not one.
 358 */
 359function quiz_feedback_for_grade($grade, $quiz, $context) {
 360    global $DB;
 361
 362    if (is_null($grade)) {
 363        return '';
 364    }
 365
 366    // With CBM etc, it is possible to get -ve grades, which would then not match
 367    // any feedback. Therefore, we replace -ve grades with 0.
 368    $grade = max($grade, 0);
 369
 370    $feedback = $DB->get_record_select('quiz_feedback',
 371            'quizid = ? AND mingrade <= ? AND ? < maxgrade', array($quiz->id, $grade, $grade));
 372
 373    if (empty($feedback->feedbacktext)) {
 374        return '';
 375    }
 376
 377    // Clean the text, ready for display.
 378    $formatoptions = new stdClass();
 379    $formatoptions->noclean = true;
 380    $feedbacktext = file_rewrite_pluginfile_urls($feedback->feedbacktext, 'pluginfile.php',
 381            $context->id, 'mod_quiz', 'feedback', $feedback->id);
 382    $feedbacktext = format_text($feedbacktext, $feedback->feedbacktextformat, $formatoptions);
 383
 384    return $feedbacktext;
 385}
 386
 387/**
 388 * @param object $quiz the quiz database row.
 389 * @return bool Whether this quiz has any non-blank feedback text.
 390 */
 391function quiz_has_feedback($quiz) {
 392    global $DB;
 393    static $cache = array();
 394    if (!array_key_exists($quiz->id, $cache)) {
 395        $cache[$quiz->id] = quiz_has_grades($quiz) &&
 396                $DB->record_exists_select('quiz_feedback', "quizid = ? AND " .
 397                    $DB->sql_isnotempty('quiz_feedback', 'feedbacktext', false, true),
 398                array($quiz->id));
 399    }
 400    return $cache[$quiz->id];
 401}
 402
 403/**
 404 * Update the sumgrades field of the quiz. This needs to be called whenever
 405 * the grading structure of the quiz is changed. For example if a question is
 406 * added or removed, or a question weight is changed.
 407 *
 408 * You should call {@link quiz_delete_previews()} before you call this function.
 409 *
 410 * @param object $quiz a quiz.
 411 */
 412function quiz_update_sumgrades($quiz) {
 413    global $DB;
 414
 415    $sql = 'UPDATE {quiz}
 416            SET sumgrades = COALESCE((
 417                SELECT SUM(grade)
 418                FROM {quiz_question_instances}
 419                WHERE quiz = {quiz}.id
 420            ), 0)
 421            WHERE id = ?';
 422    $DB->execute($sql, array($quiz->id));
 423    $quiz->sumgrades = $DB->get_field('quiz', 'sumgrades', array('id' => $quiz->id));
 424
 425    if ($quiz->sumgrades < 0.000005 && quiz_has_attempts($quiz->id)) {
 426        // If the quiz has been attempted, and the sumgrades has been
 427        // set to 0, then we must also set the maximum possible grade to 0, or
 428        // we will get a divide by zero error.
 429        quiz_set_grade(0, $quiz);
 430    }
 431}
 432
 433/**
 434 * Update the sumgrades field of the attempts at a quiz.
 435 *
 436 * @param object $quiz a quiz.
 437 */
 438function quiz_update_all_attempt_sumgrades($quiz) {
 439    global $DB;
 440    $dm = new question_engine_data_mapper();
 441    $timenow = time();
 442
 443    $sql = "UPDATE {quiz_attempts}
 444            SET
 445                timemodified = :timenow,
 446                sumgrades = (
 447                    {$dm->sum_usage_marks_subquery('uniqueid')}
 448                )
 449            WHERE quiz = :quizid AND state = :finishedstate";
 450    $DB->execute($sql, array('timenow' => $timenow, 'quizid' => $quiz->id,
 451            'finishedstate' => quiz_attempt::FINISHED));
 452}
 453
 454/**
 455 * The quiz grade is the maximum that student's results are marked out of. When it
 456 * changes, the corresponding data in quiz_grades and quiz_feedback needs to be
 457 * rescaled. After calling this function, you probably need to call
 458 * quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
 459 * quiz_update_grades.
 460 *
 461 * @param float $newgrade the new maximum grade for the quiz.
 462 * @param object $quiz the quiz we are updating. Passed by reference so its
 463 *      grade field can be updated too.
 464 * @return bool indicating success or failure.
 465 */
 466function quiz_set_grade($newgrade, $quiz) {
 467    global $DB;
 468    // This is potentially expensive, so only do it if necessary.
 469    if (abs($quiz->grade - $newgrade) < 1e-7) {
 470        // Nothing to do.
 471        return true;
 472    }
 473
 474    $oldgrade = $quiz->grade;
 475    $quiz->grade = $newgrade;
 476
 477    // Use a transaction, so that on those databases that support it, this is safer.
 478    $transaction = $DB->start_delegated_transaction();
 479
 480    // Update the quiz table.
 481    $DB->set_field('quiz', 'grade', $newgrade, array('id' => $quiz->instance));
 482
 483    if ($oldgrade < 1) {
 484        // If the old grade was zero, we cannot rescale, we have to recompute.
 485        // We also recompute if the old grade was too small to avoid underflow problems.
 486        quiz_update_all_final_grades($quiz);
 487
 488    } else {
 489        // We can rescale the grades efficiently.
 490        $timemodified = time();
 491        $DB->execute("
 492                UPDATE {quiz_grades}
 493                SET grade = ? * grade, timemodified = ?
 494                WHERE quiz = ?
 495        ", array($newgrade/$oldgrade, $timemodified, $quiz->id));
 496    }
 497
 498    if ($oldgrade > 1e-7) {
 499        // Update the quiz_feedback table.
 500        $factor = $newgrade/$oldgrade;
 501        $DB->execute("
 502                UPDATE {quiz_feedback}
 503                SET mingrade = ? * mingrade, maxgrade = ? * maxgrade
 504                WHERE quizid = ?
 505        ", array($factor, $factor, $quiz->id));
 506    }
 507
 508    // Update grade item and send all grades to gradebook.
 509    quiz_grade_item_update($quiz);
 510    quiz_update_grades($quiz);
 511
 512    $transaction->allow_commit();
 513    return true;
 514}
 515
 516/**
 517 * Save the overall grade for a user at a quiz in the quiz_grades table
 518 *
 519 * @param object $quiz The quiz for which the best grade is to be calculated and then saved.
 520 * @param int $userid The userid to calculate the grade for. Defaults to the current user.
 521 * @param array $attempts The attempts of this user. Useful if you are
 522 * looping through many users. Attempts can be fetched in one master query to
 523 * avoid repeated querying.
 524 * @return bool Indicates success or failure.
 525 */
 526function quiz_save_best_grade($quiz, $userid = null, $attempts = array()) {
 527    global $DB, $OUTPUT, $USER;
 528
 529    if (empty($userid)) {
 530        $userid = $USER->id;
 531    }
 532
 533    if (!$attempts) {
 534        // Get all the attempts made by the user.
 535        $attempts = quiz_get_user_attempts($quiz->id, $userid);
 536    }
 537
 538    // Calculate the best grade.
 539    $bestgrade = quiz_calculate_best_grade($quiz, $attempts);
 540    $bestgrade = quiz_rescale_grade($bestgrade, $quiz, false);
 541
 542    // Save the best grade in the database.
 543    if (is_null($bestgrade)) {
 544        $DB->delete_records('quiz_grades', array('quiz' => $quiz->id, 'userid' => $userid));
 545
 546    } else if ($grade = $DB->get_record('quiz_grades',
 547            array('quiz' => $quiz->id, 'userid' => $userid))) {
 548        $grade->grade = $bestgrade;
 549        $grade->timemodified = time();
 550        $DB->update_record('quiz_grades', $grade);
 551
 552    } else {
 553        $grade = new stdClass();
 554        $grade->quiz = $quiz->id;
 555        $grade->userid = $userid;
 556        $grade->grade = $bestgrade;
 557        $grade->timemodified = time();
 558        $DB->insert_record('quiz_grades', $grade);
 559    }
 560
 561    quiz_update_grades($quiz, $userid);
 562}
 563
 564/**
 565 * Calculate the overall grade for a quiz given a number of attempts by a particular user.
 566 *
 567 * @param object $quiz    the quiz settings object.
 568 * @param array $attempts an array of all the user's attempts at this quiz in order.
 569 * @return float          the overall grade
 570 */
 571function quiz_calculate_best_grade($quiz, $attempts) {
 572
 573    switch ($quiz->grademethod) {
 574
 575        case QUIZ_ATTEMPTFIRST:
 576            $firstattempt = reset($attempts);
 577            return $firstattempt->sumgrades;
 578
 579        case QUIZ_ATTEMPTLAST:
 580            $lastattempt = end($attempts);
 581            return $lastattempt->sumgrades;
 582
 583        case QUIZ_GRADEAVERAGE:
 584            $sum = 0;
 585            $count = 0;
 586            foreach ($attempts as $attempt) {
 587                if (!is_null($attempt->sumgrades)) {
 588                    $sum += $attempt->sumgrades;
 589                    $count++;
 590                }
 591            }
 592            if ($count == 0) {
 593                return null;
 594            }
 595            return $sum / $count;
 596
 597        case QUIZ_GRADEHIGHEST:
 598        default:
 599            $max = null;
 600            foreach ($attempts as $attempt) {
 601                if ($attempt->sumgrades > $max) {
 602                    $max = $attempt->sumgrades;
 603                }
 604            }
 605            return $max;
 606    }
 607}
 608
 609/**
 610 * Update the final grade at this quiz for all students.
 611 *
 612 * This function is equivalent to calling quiz_save_best_grade for all
 613 * users, but much more efficient.
 614 *
 615 * @param object $quiz the quiz settings.
 616 */
 617function quiz_update_all_final_grades($quiz) {
 618    global $DB;
 619
 620    if (!$quiz->sumgrades) {
 621        return;
 622    }
 623
 624    $param = array('iquizid' => $quiz->id, 'istatefinished' => quiz_attempt::FINISHED);
 625    $firstlastattemptjoin = "JOIN (
 626            SELECT
 627                iquiza.userid,
 628                MIN(attempt) AS firstattempt,
 629                MAX(attempt) AS lastattempt
 630
 631            FROM {quiz_attempts} iquiza
 632
 633            WHERE
 634                iquiza.state = :istatefinished AND
 635                iquiza.preview = 0 AND
 636                iquiza.quiz = :iquizid
 637
 638            GROUP BY iquiza.userid
 639        ) first_last_attempts ON first_last_attempts.userid = quiza.userid";
 640
 641    switch ($quiz->grademethod) {
 642        case QUIZ_ATTEMPTFIRST:
 643            // Because of the where clause, there will only be one row, but we
 644            // must still use an aggregate function.
 645            $select = 'MAX(quiza.sumgrades)';
 646            $join = $firstlastattemptjoin;
 647            $where = 'quiza.attempt = first_last_attempts.firstattempt AND';
 648            break;
 649
 650        case QUIZ_ATTEMPTLAST:
 651            // Because of the where clause, there will only be one row, but we
 652            // must still use an aggregate function.
 653            $select = 'MAX(quiza.sumgrades)';
 654            $join = $firstlastattemptjoin;
 655            $where = 'quiza.attempt = first_last_attempts.lastattempt AND';
 656            break;
 657
 658        case QUIZ_GRADEAVERAGE:
 659            $select = 'AVG(quiza.sumgrades)';
 660            $join = '';
 661            $where = '';
 662            break;
 663
 664        default:
 665        case QUIZ_GRADEHIGHEST:
 666            $select = 'MAX(quiza.sumgrades)';
 667            $join = '';
 668            $where = '';
 669            break;
 670    }
 671
 672    if ($quiz->sumgrades >= 0.000005) {
 673        $finalgrade = $select . ' * ' . ($quiz->grade / $quiz->sumgrades);
 674    } else {
 675        $finalgrade = '0';
 676    }
 677    $param['quizid'] = $quiz->id;
 678    $param['quizid2'] = $quiz->id;
 679    $param['quizid3'] = $quiz->id;
 680    $param['quizid4'] = $quiz->id;
 681    $param['statefinished'] = quiz_attempt::FINISHED;
 682    $param['statefinished2'] = quiz_attempt::FINISHED;
 683    $finalgradesubquery = "
 684            SELECT quiza.userid, $finalgrade AS newgrade
 685            FROM {quiz_attempts} quiza
 686            $join
 687            WHERE
 688                $where
 689                quiza.state = :statefinished AND
 690                quiza.preview = 0 AND
 691                quiza.quiz = :quizid3
 692            GROUP BY quiza.userid";
 693
 694    $changedgrades = $DB->get_records_sql("
 695            SELECT users.userid, qg.id, qg.grade, newgrades.newgrade
 696
 697            FROM (
 698                SELECT userid
 699                FROM {quiz_grades} qg
 700                WHERE quiz = :quizid
 701            UNION
 702                SELECT DISTINCT userid
 703                FROM {quiz_attempts} quiza2
 704                WHERE
 705                    quiza2.state = :statefinished2 AND
 706                    quiza2.preview = 0 AND
 707                    quiza2.quiz = :quizid2
 708            ) users
 709
 710            LEFT JOIN {quiz_grades} qg ON qg.userid = users.userid AND qg.quiz = :quizid4
 711
 712            LEFT JOIN (
 713                $finalgradesubquery
 714            ) newgrades ON newgrades.userid = users.userid
 715
 716            WHERE
 717                ABS(newgrades.newgrade - qg.grade) > 0.000005 OR
 718                ((newgrades.newgrade IS NULL OR qg.grade IS NULL) AND NOT
 719                          (newgrades.newgrade IS NULL AND qg.grade IS NULL))",
 720                // The mess on the previous line is detecting where the value is
 721                // NULL in one column, and NOT NULL in the other, but SQL does
 722                // not have an XOR operator, and MS SQL server can't cope with
 723                // (newgrades.newgrade IS NULL) <> (qg.grade IS NULL).
 724            $param);
 725
 726    $timenow = time();
 727    $todelete = array();
 728    foreach ($changedgrades as $changedgrade) {
 729
 730        if (is_null($changedgrade->newgrade)) {
 731            $todelete[] = $changedgrade->userid;
 732
 733        } else if (is_null($changedgrade->grade)) {
 734            $toinsert = new stdClass();
 735            $toinsert->quiz = $quiz->id;
 736            $toinsert->userid = $changedgrade->userid;
 737            $toinsert->timemodified = $timenow;
 738            $toinsert->grade = $changedgrade->newgrade;
 739            $DB->insert_record('quiz_grades', $toinsert);
 740
 741        } else {
 742            $toupdate = new stdClass();
 743            $toupdate->id = $changedgrade->id;
 744            $toupdate->grade = $changedgrade->newgrade;
 745            $toupdate->timemodified = $timenow;
 746            $DB->update_record('quiz_grades', $toupdate);
 747        }
 748    }
 749
 750    if (!empty($todelete)) {
 751        list($test, $params) = $DB->get_in_or_equal($todelete);
 752        $DB->delete_records_select('quiz_grades', 'quiz = ? AND userid ' . $test,
 753                array_merge(array($quiz->id), $params));
 754    }
 755}
 756
 757/**
 758 * Return the attempt with the best grade for a quiz
 759 *
 760 * Which attempt is the best depends on $quiz->grademethod. If the grade
 761 * method is GRADEAVERAGE then this function simply returns the last attempt.
 762 * @return object         The attempt with the best grade
 763 * @param object $quiz    The quiz for which the best grade is to be calculated
 764 * @param array $attempts An array of all the attempts of the user at the quiz
 765 */
 766function quiz_calculate_best_attempt($quiz, $attempts) {
 767
 768    switch ($quiz->grademethod) {
 769
 770        case QUIZ_ATTEMPTFIRST:
 771            foreach ($attempts as $attempt) {
 772                return $attempt;
 773            }
 774            break;
 775
 776        case QUIZ_GRADEAVERAGE: // We need to do something with it.
 777        case QUIZ_ATTEMPTLAST:
 778            foreach ($attempts as $attempt) {
 779                $final = $attempt;
 780            }
 781            return $final;
 782
 783        default:
 784        case QUIZ_GRADEHIGHEST:
 785            $max = -1;
 786            foreach ($attempts as $attempt) {
 787                if ($attempt->sumgrades > $max) {
 788                    $max = $attempt->sumgrades;
 789                    $maxattempt = $attempt;
 790                }
 791            }
 792            return $maxattempt;
 793    }
 794}
 795
 796/**
 797 * @return array int => lang string the options for calculating the quiz grade
 798 *      from the individual attempt grades.
 799 */
 800function quiz_get_grading_options() {
 801    return array(
 802        QUIZ_GRADEHIGHEST => get_string('gradehighest', 'quiz'),
 803        QUIZ_GRADEAVERAGE => get_string('gradeaverage', 'quiz'),
 804        QUIZ_ATTEMPTFIRST => get_string('attemptfirst', 'quiz'),
 805        QUIZ_ATTEMPTLAST  => get_string('attemptlast', 'quiz')
 806    );
 807}
 808
 809/**
 810 * @param int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
 811 *      QUIZ_ATTEMPTFIRST or QUIZ_ATTEMPTLAST.
 812 * @return the lang string for that option.
 813 */
 814function quiz_get_grading_option_name($option) {
 815    $strings = quiz_get_grading_options();
 816    return $strings[$option];
 817}
 818
 819/**
 820 * @return array string => lang string the options for handling overdue quiz
 821 *      attempts.
 822 */
 823function quiz_get_overdue_handling_options() {
 824    return array(
 825        'autosubmit'  => get_string('overduehandlingautosubmit', 'quiz'),
 826        'graceperiod' => get_string('overduehandlinggraceperiod', 'quiz'),
 827        'autoabandon' => get_string('overduehandlingautoabandon', 'quiz'),
 828    );
 829}
 830
 831/**
 832 * @param string $state one of the state constants like IN_PROGRESS.
 833 * @return string the human-readable state name.
 834 */
 835function quiz_attempt_state_name($state) {
 836    switch ($state) {
 837        case quiz_attempt::IN_PROGRESS:
 838            return get_string('stateinprogress', 'quiz');
 839        case quiz_attempt::OVERDUE:
 840            return get_string('stateoverdue', 'quiz');
 841        case quiz_attempt::FINISHED:
 842            return get_string('statefinished', 'quiz');
 843        case quiz_attempt::ABANDONED:
 844            return get_string('stateabandoned', 'quiz');
 845        default:
 846            throw new coding_exception('Unknown quiz attempt state.');
 847    }
 848}
 849
 850// Other quiz functions ////////////////////////////////////////////////////////
 851
 852/**
 853 * @param object $quiz the quiz.
 854 * @param int $cmid the course_module object for this quiz.
 855 * @param object $question the question.
 856 * @param string $returnurl url to return to after action is done.
 857 * @return string html for a number of icons linked to action pages for a
 858 * question - preview and edit / view icons depending on user capabilities.
 859 */
 860function quiz_question_action_icons($quiz, $cmid, $question, $returnurl) {
 861    $html = quiz_question_preview_button($quiz, $question) . ' ' .
 862            quiz_question_edit_button($cmid, $question, $returnurl);
 863    return $html;
 864}
 865
 866/**
 867 * @param int $cmid the course_module.id for this quiz.
 868 * @param object $question the question.
 869 * @param string $returnurl url to return to after action is done.
 870 * @param string $contentbeforeicon some HTML content to be added inside the link, before the icon.
 871 * @return the HTML for an edit icon, view icon, or nothing for a question
 872 *      (depending on permissions).
 873 */
 874function quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '') {
 875    global $CFG, $OUTPUT;
 876
 877    // Minor efficiency saving. Only get strings once, even if there are a lot of icons on one page.
 878    static $stredit = null;
 879    static $strview = null;
 880    if ($stredit === null) {
 881        $stredit = get_string('edit');
 882        $strview = get_string('view');
 883    }
 884
 885    // What sort of icon should we show?
 886    $action = '';
 887    if (!empty($question->id) &&
 888            (question_has_capability_on($question, 'edit', $question->category) ||
 889                    question_has_capability_on($question, 'move', $question->category))) {
 890        $action = $stredit;
 891        $icon = '/t/edit';
 892    } else if (!empty($question->id) &&
 893            question_has_capability_on($question, 'view', $question->category)) {
 894        $action = $strview;
 895        $icon = '/i/info';
 896    }
 897
 898    // Build the icon.
 899    if ($action) {
 900        if ($returnurl instanceof moodle_url) {
 901            $returnurl = $returnurl->out_as_local_url(false);
 902        }
 903        $questionparams = array('returnurl' => $returnurl, 'cmid' => $cmid, 'id' => $question->id);
 904        $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
 905        return '<a title="' . $action . '" href="' . $questionurl->out() . '" class="questioneditbutton"><img src="' .
 906                $OUTPUT->pix_url($icon) . '" alt="' . $action . '" />' . $contentaftericon .
 907                '</a>';
 908    } else if ($contentaftericon) {
 909        return '<span class="questioneditbutton">' . $contentaftericon . '</span>';
 910    } else {
 911        return '';
 912    }
 913}
 914
 915/**
 916 * @param object $quiz the quiz settings
 917 * @param object $question the question
 918 * @return moodle_url to preview this question with the options from this quiz.
 919 */
 920function quiz_question_preview_url($quiz, $question) {
 921    // Get the appropriate display options.
 922    $displayoptions = mod_quiz_display_options::make_from_quiz($quiz,
 923            mod_quiz_display_options::DURING);
 924
 925    $maxmark = null;
 926    if (isset($question->maxmark)) {
 927        $maxmark = $question->maxmark;
 928    }
 929
 930    // Work out the correcte preview URL.
 931    return question_preview_url($question->id, $quiz->preferredbehaviour,
 932            $maxmark, $displayoptions);
 933}
 934
 935/**
 936 * @param object $quiz the quiz settings
 937 * @param object $question the question
 938 * @param bool $label if true, show the preview question label after the icon
 939 * @return the HTML for a preview question icon.
 940 */
 941function quiz_question_preview_button($quiz, $question, $label = false) {
 942    global $CFG, $OUTPUT;
 943    if (!question_has_capability_on($question, 'use', $question->category)) {
 944        return '';
 945    }
 946
 947    $url = quiz_question_preview_url($quiz, $question);
 948
 949    // Do we want a label?
 950    $strpreviewlabel = '';
 951    if ($label) {
 952        $strpreviewlabel = get_string('preview', 'quiz');
 953    }
 954
 955    // Build the icon.
 956    $strpreviewquestion = get_string('previewquestion', 'quiz');
 957    $image = $OUTPUT->pix_icon('t/preview', $strpreviewquestion);
 958
 959    $action = new popup_action('click', $url, 'questionpreview',
 960            question_preview_popup_params());
 961
 962    return $OUTPUT->action_link($url, $image, $action, array('title' => $strpreviewquestion));
 963}
 964
 965/**
 966 * @param object $attempt the attempt.
 967 * @param object $context the quiz context.
 968 * @return int whether flags should be shown/editable to the current user for this attempt.
 969 */
 970function quiz_get_flag_option($attempt, $context) {
 971    global $USER;
 972    if (!has_capability('moodle/question:flag', $context)) {
 973        return question_display_options::HIDDEN;
 974    } else if ($attempt->userid == $USER->id) {
 975        return question_display_options::EDITABLE;
 976    } else {
 977        return question_display_options::VISIBLE;
 978    }
 979}
 980
 981/**
 982 * Work out what state this quiz attempt is in - in the sense used by
 983 * quiz_get_review_options, not in the sense of $attempt->state.
 984 * @param object $quiz the quiz settings
 985 * @param object $attempt the quiz_attempt database row.
 986 * @return int one of the mod_quiz_display_options::DURING,
 987 *      IMMEDIATELY_AFTER, LATER_WHILE_OPEN or AFTER_CLOSE constants.
 988 */
 989function quiz_attempt_state($quiz, $attempt) {
 990    if ($attempt->state != quiz_attempt::FINISHED) {
 991        return mod_quiz_display_options::DURING;
 992    } else if (time() < $attempt->timefinish + 120) {
 993        return mod_quiz_display_options::IMMEDIATELY_AFTER;
 994    } else if (!$quiz->timeclose || time() < $quiz->timeclose) {
 995        return mod_quiz_display_options::LATER_WHILE_OPEN;
 996    } else {
 997        return mod_quiz_display_options::AFTER_CLOSE;
 998    }
 999}
1000
1001/**
1002 * The the appropraite mod_quiz_display_options object for this attempt at this
1003 * quiz right now.
1004 *
1005 * @param object $quiz the quiz instance.
1006 * @param object $attempt the attempt in question.
1007 * @param $context the quiz context.
1008 *
1009 * @return mod_quiz_display_options
1010 */
1011function quiz_get_review_options($quiz, $attempt, $context) {
1012    $options = mod_quiz_display_options::make_from_quiz($quiz, quiz_attempt_state($quiz, $attempt));
1013
1014    $options->readonly = true;
1015    $options->flags = quiz_get_flag_option($attempt, $context);
1016    if (!empty($attempt->id)) {
1017        $options->questionreviewlink = new moodle_url('/mod/quiz/reviewquestion.php',
1018                array('attempt' => $attempt->id));
1019    }
1020
1021    // Show a link to the comment box only for closed attempts.
1022    if (!empty($attempt->id) && $attempt->state == quiz_attempt::FINISHED && !$attempt->preview &&
1023            !is_null($context) && has_capability('mod/quiz:grade', $context)) {
1024        $options->manualcomment = question_display_options::VISIBLE;
1025        $options->manualcommentlink = new moodle_url('/mod/quiz/comment.php',
1026                array('attempt' => $attempt->id));
1027    }
1028
1029    if (!is_null($context) && !$attempt->preview &&
1030            has_capability('mod/quiz:viewreports', $context) &&
1031            has_capability('moodle/grade:viewhidden', $context)) {
1032        // People who can see reports and hidden grades should be shown everything,
1033        // except during preview when teachers want to see what students see.
1034        $options->attempt = question_display_options::VISIBLE;
1035        $options->correctness = question_display_options::VISIBLE;
1036        $options->marks = question_display_options::MARK_AND_MAX;
1037        $options->feedback = question_display_options::VISIBLE;
1038        $options->numpartscorrect = question_display_options::VISIBLE;
1039        $options->generalfeedback = question_display_options::VISIBLE;
1040        $options->rightanswer = question_display_options::VISIBLE;
1041        $options->overallfeedback = question_display_options::VISIBLE;
1042        $options->history = question_display_options::VISIBLE;
1043
1044    }
1045
1046    return $options;
1047}
1048
1049/**
1050 * Combines the review options from a number of different quiz attempts.
1051 * Returns an array of two ojects, so the suggested way of calling this
1052 * funciton is:
1053 * list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)
1054 *
1055 * @param object $quiz the quiz instance.
1056 * @param array $attempts an array of attempt objects.
1057 * @param $context the roles and permissions context,
1058 *          normally the context for the quiz module instance.
1059 *
1060 * @return array of two options objects, one showing which options are true for
1061 *          at least one of the attempts, the other showing which options are true
1062 *          for all attempts.
1063 */
1064function quiz_get_combined_reviewoptions($quiz, $attempts) {
1065    $fields = array('feedback', 'generalfeedback', 'rightanswer', 'overallfeedback');
1066    $someoptions = new stdClass();
1067    $alloptions = new stdClass();
1068    foreach ($fields as $field) {
1069        $someoptions->$field = false;
1070        $alloptions->$field = true;
1071    }
1072    $someoptions->marks = question_display_options::HIDDEN;
1073    $alloptions->marks = question_display_options::MARK_AND_MAX;
1074
1075    foreach ($attempts as $attempt) {
1076        $attemptoptions = mod_quiz_display_options::make_from_quiz($quiz,
1077                quiz_attempt_state($quiz, $attempt));
1078        foreach ($fields as $field) {
1079            $someoptions->$field = $someoptions->$field || $attemptoptions->$field;
1080            $alloptions->$field = $alloptions->$field && $attemptoptions->$field;
1081        }
1082        $someoptions->marks = max($someoptions->marks, $attemptoptions->marks);
1083        $alloptions->marks = min($alloptions->marks, $attemptoptions->marks);
1084    }
1085    return array($someoptions, $alloptions);
1086}
1087
1088/**
1089 * Clean the question layout from various possible anomalies:
1090 * - Remove consecutive ","'s
1091 * - Remove duplicate question id's
1092 * - Remove extra "," from beginning and end
1093 * - Finally, add a ",0" in the end if there is none
1094 *
1095 * @param $string $layout the quiz layout to clean up, usually from $quiz->questions.
1096 * @param bool $removeemptypages If true, remove empty pages from the quiz. False by default.
1097 * @return $string the cleaned-up layout
1098 */
1099function quiz_clean_layout($layout, $removeemptypages = false) {
1100    // Remove repeated ','s. This can happen when a restore fails to find the right
1101    // id to relink to.
1102    $layout = preg_replace('/,{2,}/', ',', trim($layout, ','));
1103
1104    // Remove duplicate question ids.
1105    $layout = explode(',', $layout);
1106    $cleanerlayout = array();
1107    $seen = array();
1108    foreach ($layout as $item) {
1109        if ($item == 0) {
1110            $cleanerlayout[] = '0';
1111        } else if (!in_array($item, $seen)) {
1112            $cleanerlayout[] = $item;
1113            $seen[] = $item;
1114        }
1115    }
1116
1117    if ($removeemptypages) {
1118        // Avoid duplicate page breaks.
1119        $layout = $cleanerlayout;
1120        $cleanerlayout = array();
1121        $stripfollowingbreaks = true; // Ensure breaks are stripped from the start.
1122        foreach ($layout as $item) {
1123            if ($stripfollowingbreaks && $item == 0) {
1124                continue;
1125            }
1126            $cleanerlayout[] = $item;
1127            $stripfollowingbreaks = $item == 0;
1128        }
1129    }
1130
1131    // Add a page break at the end if there is none.
1132    if (end($cleanerlayout) !== '0') {
1133        $cleanerlayout[] = '0';
1134    }
1135
1136    return implode(',', $cleanerlayout);
1137}
1138
1139/**
1140 * Get the slot for a question with a particular id.
1141 * @param object $quiz the quiz settings.
1142 * @param int $questionid the of a question in the quiz.
1143 * @return int the corresponding slot. Null if the question is not in the quiz.
1144 */
1145function quiz_get_slot_for_question($quiz, $questionid) {
1146    $questionids = quiz_questions_in_quiz($quiz->questions);
1147    foreach (explode(',', $questionids) as $key => $id) {
1148        if ($id == $questionid) {
1149            return $key + 1;
1150        }
1151    }
1152    return null;
1153}
1154
1155// Functions for sending notification messages /////////////////////////////////
1156
1157/**
1158 * Sends a confirmation message to the student confirming that the attempt was processed.
1159 *
1160 * @param object $a lots of useful information that can be used in the message
1161 *      subject and body.
1162 *
1163 * @return int|false as for {@link message_send()}.
1164 */
1165function quiz_send_confirmation($recipient, $a) {
1166
1167    // Add information about the recipient to $a.
1168    // Don't do idnumber. we want idnumber to be the submitter's idnumber.
1169    $a->username     = fullname($recipient);
1170    $a->userusername = $recipient->username;
1171
1172    // Prepare the message.
1173    $eventdata = new stdClass();
1174    $eventdata->component         = 'mod_quiz';
1175    $eventdata->name              = 'confirmation';
1176    $eventdata->notification      = 1;
1177
1178    $eventdata->userfrom          = get_admin();
1179    $eventdata->userto            = $recipient;
1180    $eventdata->subject           = get_string('emailconfirmsubject', 'quiz', $a);
1181    $eventdata->fullmessage       = get_string('emailconfirmbody', 'quiz', $a);
1182    $eventdata->fullmessageformat = FORMAT_PLAIN;
1183    $eventdata->fullmessagehtml   = '';
1184
1185    $eventdata->smallmessage      = get_string('emailconfirmsmall', 'quiz', $a);
1186    $eventdata->contexturl        = $a->quizurl;
1187    $eventdata->contexturlname    = $a->quizname;
1188
1189    // ... and send it.
1190    return message_send($eventdata);
1191}
1192
1193/**
1194 * Sends notification messages to the interested parties that assign the role capability
1195 *
1196 * @param object $recipient user object of the intended recipient
1197 * @param object $a associative array of replaceable fields for the templates
1198 *
1199 * @return int|false as for {@link message_send()}.
1200 */
1201function quiz_send_notification($recipient, $submitter, $a) {
1202
1203    // Recipient info for template.
1204    $a->useridnumber = $recipient->idnumber;
1205    $a->username     = fullname($recipient);
1206    $a->userusername = $recipient->username;
1207
1208    // Prepare the message.
1209    $eventdata = new stdClass();
1210    $eventdata->component         = 'mod_quiz';
1211    $eventdata->name              = 'submission';
1212    $eventdata->notification      = 1;
1213
1214    $eventdata->userfrom          = $submitter;
1215    $eventdata->userto            = $recipient;
1216    $eventdata->subject           = get_string('emailnotifysubject', 'quiz', $a);
1217    $eventdata->fullmessage       = get_string('emailnotifybody', 'quiz', $a);
1218    $eventdata->fullmessageformat = FORMAT_PLAIN;
1219    $eventdata->fullmessagehtml   = '';
1220
1221    $eventdata->smallmessage      = get_string('emailnotifysmall', 'quiz', $a);
1222    $eventdata->contexturl        = $a->quizreviewurl;
1223    $eventdata->contexturlname    = $a->quizname;
1224
1225    // ... and send it.
1226    return message_send($eventdata);
1227}
1228
1229/**
1230 * Send all the requried messages when a quiz attempt is submitted.
1231 *
1232 * @param object $course the course
1233 * @param object $quiz the quiz
1234 * @param object $attempt this attempt just finished
1235 * @param object $context the quiz context
1236 * @param object $cm the coursemodule for this quiz
1237 *
1238 * @return bool true if all necessary messages were sent successfully, else false.
1239 */
1240function quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm) {
1241    global $CFG, $DB;
1242
1243    // Do nothing if required objects not present.
1244    if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1245        throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1246    }
1247
1248    $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1249
1250    // Check for confirmation required.
1251    $sendconfirm = false;
1252    $notifyexcludeusers = '';
1253    if (has_capability('mod/quiz:emailconfirmsubmission', $context, $submitter, false)) {
1254        $notifyexcludeusers = $submitter->id;
1255        $sendconfirm = true;
1256    }
1257
1258    // Check for notifications required.
1259    $notifyfields = 'u.id, u.username, u.firstname, u.lastname, u.idnumber, u.email, u.emailstop, ' .
1260            'u.lang, u.timezone, u.mailformat, u.maildisplay';
1261    $groups = groups_get_all_groups($course->id, $submitter->id);
1262    if (is_array($groups) && count($groups) > 0) {
1263        $groups = array_keys($groups);
1264    } else if (groups_get_activity_groupmode($cm, $course) != NOGROUPS) {
1265        // If the user is not in a group, and the quiz is set to group mode,
1266        // then set $groups to a non-existant id so that only users with
1267        // 'moodle/site:accessallgroups' get notified.
1268        $groups = -1;
1269    } else {
1270        $groups = '';
1271    }
1272    $userstonotify = get_users_by_capability($context, 'mod/quiz:emailnotifysubmission',
1273            $notifyfields, '', '', '', $groups, $notifyexcludeusers, false, false, true);
1274
1275    if (empty($userstonotify) && !$sendconfirm) {
1276        return true; // Nothing to do.
1277    }
1278
1279    $a = new stdClass();
1280    // Course info.
1281    $a->coursename      = $course->fullname;
1282    $a->courseshortname = $course->shortname;
1283    // Quiz info.
1284    $a->quizname        = $quiz->name;
1285    $a->quizreporturl   = $CFG->wwwroot . '/mod/quiz/report.php?id=' . $cm->id;
1286    $a->quizreportlink  = '<a href="' . $a->quizreporturl . '">' .
1287            format_string($quiz->name) . ' report</a>';
1288    $a->quizurl         = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1289    $a->quizlink        = '<a href="' . $a->quizurl . '">' . format_string($quiz->name) . '</a>';
1290    // Attempt info.
1291    $a->submissiontime  = userdate($attempt->timefinish);
1292    $a->timetaken       = format_time($attempt->timefinish - $attempt->timestart);
1293    $a->quizreviewurl   = $CFG->wwwroot . '/mod/quiz/review.php?attempt=' . $attempt->id;
1294    $a->quizreviewlink  = '<a href="' . $a->quizreviewurl . '">' .
1295            format_string($quiz->name) . ' review</a>';
1296    // Student who sat the quiz info.
1297    $a->studentidnumber = $submitter->idnumber;
1298    $a->studentname     = fullname($submitter);
1299    $a->studentusername = $submitter->username;
1300
1301    $allok = true;
1302
1303    // Send notifications if required.
1304    if (!empty($userstonotify)) {
1305        foreach ($userstonotify as $recipient) {
1306            $allok = $allok && quiz_send_notification($recipient, $submitter, $a);
1307        }
1308    }
1309
1310    // Send confirmation if required. We send the student confirmation last, so
1311    // that if message sending is being intermittently buggy, which means we send
1312    // some but not all messages, and then try again later, then teachers may get
1313    // duplicate messages, but the student will always get exactly one.
1314    if ($sendconfirm) {
1315        $allok = $allok && quiz_send_confirmation($submitter, $a);
1316    }
1317
1318    return $allok;
1319}
1320
1321/**
1322 * Send the notification message when a quiz attempt becomes overdue.
1323 *
1324 * @param object $course the course
1325 * @param object $quiz the quiz
1326 * @param object $attempt this attempt just finished
1327 * @param object $context the quiz context
1328 * @param object $cm the coursemodule for this quiz
1329 */
1330function quiz_send_overdue_message($course, $quiz, $attempt, $context, $cm) {
1331    global $CFG, $DB;
1332
1333    // Do nothing if required objects not present.
1334    if (empty($course) or empty($quiz) or empty($attempt) or empty($context)) {
1335        throw new coding_exception('$course, $quiz, $attempt, $context and $cm must all be set.');
1336    }
1337
1338    $submitter = $DB->get_record('user', array('id' => $attempt->userid), '*', MUST_EXIST);
1339
1340    if (!has_capability('mod/quiz:emailwarnoverdue', $context, $submitter, false)) {
1341        return; // Message not required.
1342    }
1343
1344    // Prepare lots of useful information that admins might want to include in
1345    // the email message.
1346    $quizname = format_string($quiz->name);
1347
1348    $deadlines = array();
1349    if ($quiz->timelimit) {
1350        $deadlines[] = $attempt->timestart + $quiz->timelimit;
1351    }
1352    if ($quiz->timeclose) {
1353        $deadlines[] = $quiz->timeclose;
1354    }
1355    $duedate = min($deadlines);
1356    $graceend = $duedate + $quiz->graceperiod;
1357
1358    $a = new stdClass();
1359    // Course info.
1360    $a->coursename         = $course->fullname;
1361    $a->courseshortname    = $course->shortname;
1362    // Quiz info.
1363    $a->quizname           = $quizname;
1364    $a->quizurl            = $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1365    $a->quizlink           = '<a href="' . $a->quizurl . '">' . $quizname . '</a>';
1366    // Attempt info.
1367    $a->attemptduedate    = userdate($duedate);
1368    $a->attemptgraceend    = userdate($graceend);
1369    $a->attemptsummaryurl  = $CFG->wwwroot . '/mod/quiz/summary.php?attempt=' . $attempt->id;
1370    $a->attemptsummarylink = '<a href="' . $a->attemptsummaryurl . '">' . $quizname . ' review</a>';
1371    // Student's info.
1372    $a->studentidnumber    = $submitter->idnumber;
1373    $a->studentname        = fullname($submitter);
1374    $a->studentusername    = $submitter->username;
1375
1376    // Prepare the message.
1377    $eventdata = new stdClass();
1378    $eventdata->component         = 'mod_quiz';
1379    $eventdata->name              = 'attempt_overdue';
1380    $eventdata->notification      = 1;
1381
1382    $eventdata->userfrom          = get_admin();
1383    $eventdata->userto            = $submitter;
1384    $eventdata->subject           = get_string('emailoverduesubject', 'quiz', $a);
1385    $eventdata->fullmessage       = get_string('emailoverduebody', 'quiz', $a);
1386    $eventdata->fullmessageformat = FORMAT_PLAIN;
1387    $eventdata->fullmessagehtml   = '';
1388
1389    $eventdata->smallmessage      = get_string('emailoverduesmall', 'quiz', $a);
1390    $eventdata->contexturl        = $a->quizurl;
1391    $eventdata->contexturlname    = $a->quizname;
1392
1393    // Send the message.
1394    re…

Large files files are truncated, but you can click here to view the full file