Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [Versions 402 and 403]

Library of functions used by the quiz module. This contains functions that are called from within the quiz module only Functions that are also called by core Moodle are in {@link lib.php} This script also loads the code in {@link questionlib.php} which holds the module-indpendent code for handling questions and which in turn initialises all the questiontype classes.

Copyright: 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 2178 lines (85 kb)
Included or required: 3 times
Referenced: 35 times
Includes or requires: 0 files

Defines 49 functions

  quiz_create_attempt()
  quiz_start_new_attempt()
  quiz_start_attempt_built_on_last()
  quiz_attempt_save_started()
  quiz_get_user_attempt_unfinished()
  quiz_delete_attempt()
  quiz_delete_previews()
  quiz_has_attempts()
  quiz_repaginate_questions()
  quiz_rescale_grade()
  quiz_feedback_record_for_grade()
  quiz_feedback_for_grade()
  quiz_has_feedback()
  quiz_override_summary()
  quiz_update_open_attempts()
  quiz_get_attempt_usertime_sql()
  quiz_get_grading_options()
  quiz_get_grading_option_name()
  quiz_get_overdue_handling_options()
  quiz_get_user_image_options()
  quiz_get_user_timeclose()
  quiz_questions_per_page_options()
  quiz_attempt_state_name()
  quiz_question_action_icons()
  quiz_question_edit_button()
  quiz_question_preview_url()
  quiz_question_preview_button()
  quiz_get_flag_option()
  quiz_attempt_state()
  quiz_get_review_options()
  quiz_get_combined_reviewoptions()
  quiz_send_confirmation()
  quiz_send_notification()
  quiz_send_notification_messages()
  quiz_send_overdue_message()
  quiz_attempt_submitted_handler()
  quiz_send_notify_manual_graded_message()
  quiz_process_group_deleted_in_course()
  quiz_get_js_module()
  quiz_question_tostring()
  quiz_require_question_use()
  quiz_add_quiz_question()
  quiz_update_section_firstslots()
  quiz_add_random_questions()
  quiz_view()
  quiz_validate_new_attempt()
  quiz_prepare_and_start_new_attempt()
  quiz_is_overriden_calendar_event()
  quiz_create_attempt_handling_errors()

Functions that are not part of a class:

quiz_create_attempt(quiz_settings $quizobj, $attemptnumber, $lastattempt, $timenow, $ispreview = false, $userid = null)   X-Ref
Creates an object to represent a new attempt at a quiz

Creates an attempt object to represent an attempt at the quiz by the current
user starting at the current time. The ->id field is not set. The object is
NOT written to the database.

param: quiz_settings $quizobj the quiz object to create an attempt for.
param: int $attemptnumber the sequence number for the attempt.
param: stdClass|false $lastattempt the previous attempt by this user, if any. Only needed
param: int $timenow the time the attempt was started at.
param: bool $ispreview whether this new attempt is a preview.
param: int|null $userid  the id of the user attempting this quiz.
return: stdClass the newly created attempt object.

quiz_start_new_attempt($quizobj, $quba, $attempt, $attemptnumber, $timenow,$questionids = [], $forcedvariantsbyslot = [])   X-Ref
Start a normal, new, quiz attempt.

param: quiz_settings $quizobj        the quiz object to start an attempt for.
param: question_usage_by_activity $quba
param: stdClass    $attempt
param: integer   $attemptnumber      starting from 1
param: integer   $timenow            the attempt start time
param: array     $questionids        slot number => question id. Used for random questions, to force the choice
param: array     $forcedvariantsbyslot slot number => variant. Used for questions with variants,
return: stdClass   modified attempt object

quiz_start_attempt_built_on_last($quba, $attempt, $lastattempt)   X-Ref
Start a subsequent new attempt, in each attempt builds on last mode.

param: question_usage_by_activity    $quba         this question usage
param: stdClass                        $attempt      this attempt
param: stdClass                        $lastattempt  last attempt
return: stdClass                       modified attempt object

quiz_attempt_save_started($quizobj, $quba, $attempt)   X-Ref
The save started question usage and quiz attempt in db and log the started attempt.

param: quiz_settings $quizobj
param: question_usage_by_activity $quba
param: stdClass                     $attempt
return: stdClass                    attempt object with uniqueid and id set.

quiz_get_user_attempt_unfinished($quizid, $userid)   X-Ref
Returns an unfinished attempt (if there is one) for the given
user on the given quiz. This function does not return preview attempts.

param: int $quizid the id of the quiz.
param: int $userid the id of the user.
return: mixed the unfinished attempt if there is one, false if not.

quiz_delete_attempt($attempt, $quiz)   X-Ref
Delete a quiz attempt.

param: mixed $attempt an integer attempt id or an attempt object
param: stdClass $quiz the quiz object.

quiz_delete_previews($quiz, $userid = null)   X-Ref
Delete all the preview attempts at a quiz, or possibly all the attempts belonging
to one user.

param: stdClass $quiz the quiz object.
param: int $userid (optional) if given, only delete the previews belonging to this user.

quiz_has_attempts($quizid)   X-Ref

param: int $quizid The quiz id.
return: bool whether this quiz has any (non-preview) attempts.

quiz_repaginate_questions($quizid, $slotsperpage)   X-Ref
Repaginate the questions in a quiz

param: int $quizid the id of the quiz to repaginate.
param: int $slotsperpage number of items to put on each page. 0 means unlimited.

quiz_rescale_grade($rawgrade, $quiz, $format = true)   X-Ref
Convert the raw grade stored in $attempt into a grade out of the maximum
grade for this quiz.

param: float $rawgrade the unadjusted grade, fof example $attempt->sumgrades
param: stdClass $quiz the quiz object. Only the fields grade, sumgrades and decimalpoints are used.
param: bool|string $format whether to format the results for display
return: float|string the rescaled grade, or null/the lang string 'notyetgraded'

quiz_feedback_record_for_grade($grade, $quiz)   X-Ref
Get the feedback object for this grade on this quiz.

param: float $grade a grade on this quiz.
param: stdClass $quiz the quiz settings.
return: false|stdClass the record object or false if there is not feedback for the given grade

quiz_feedback_for_grade($grade, $quiz, $context)   X-Ref
Get the feedback text that should be show to a student who
got this grade on this quiz. The feedback is processed ready for diplay.

param: float $grade a grade on this quiz.
param: stdClass $quiz the quiz settings.
param: context_module $context the quiz context.
return: string the comment that corresponds to this grade (empty string if there is not one.

quiz_has_feedback($quiz)   X-Ref

param: stdClass $quiz the quiz database row.
return: bool Whether this quiz has any non-blank feedback text.

quiz_override_summary(stdClass $quiz, cm_info|stdClass $cm, int $currentgroup = 0)   X-Ref
Return summary of the number of settings override that exist.

To get a nice display of this, see the quiz_override_summary_links()
quiz renderer method.

param: stdClass $quiz the quiz settings. Only $quiz->id is used at the moment.
param: cm_info|stdClass $cm the cm object. Only $cm->course, $cm->groupmode and
param: int $currentgroup if there is a concept of current group where this method is being called
return: array like 'group' => 3, 'user' => 12] where 3 is the number of group overrides,

quiz_update_open_attempts(array $conditions)   X-Ref
Efficiently update check state time on all open attempts

param: array $conditions optional restrictions on which attempts to update

quiz_get_attempt_usertime_sql($redundantwhereclauses = '')   X-Ref
Returns SQL to compute timeclose and timelimit for every attempt, taking into account user and group overrides.
The query used herein is very similar to the one in function quiz_get_user_timeclose, so, in case you
would change either one of them, make sure to apply your changes to both.

param: string $redundantwhereclauses extra where clauses to add to the subquery
return: string SQL select with columns attempt.id, usertimeclose, usertimelimit.

quiz_get_grading_options()   X-Ref

return: array int => lang string the options for calculating the quiz grade

quiz_get_grading_option_name($option)   X-Ref

param: int $option one of the values QUIZ_GRADEHIGHEST, QUIZ_GRADEAVERAGE,
return: the lang string for that option.

quiz_get_overdue_handling_options()   X-Ref

return: array string => lang string the options for handling overdue quiz

quiz_get_user_image_options()   X-Ref
Get the choices for what size user picture to show.

return: array string => lang string the options for whether to display the user's picture.

quiz_get_user_timeclose($courseid)   X-Ref
Return an user's timeclose for all quizzes in a course, hereby taking into account group and user overrides.

param: int $courseid the course id.
return: stdClass An object with of all quizids and close unixdates in this course, taking into account the most lenient

quiz_questions_per_page_options()   X-Ref
Get the choices to offer for the 'Questions per page' option.

return: array int => string.

quiz_attempt_state_name($state)   X-Ref
Get the human-readable name for a quiz attempt state.

param: string $state one of the state constants like {@see quiz_attempt::IN_PROGRESS}.
return: string The lang string to describe that state.

quiz_question_action_icons($quiz, $cmid, $question, $returnurl, $variant = null)   X-Ref

param: stdClass $quiz the quiz.
param: int $cmid the course_module object for this quiz.
param: stdClass $question the question.
param: string $returnurl url to return to after action is done.
param: int $variant which question variant to preview (optional).
return: string html for a number of icons linked to action pages for a

quiz_question_edit_button($cmid, $question, $returnurl, $contentaftericon = '')   X-Ref

param: int $cmid the course_module.id for this quiz.
param: stdClass $question the question.
param: string $returnurl url to return to after action is done.
param: string $contentbeforeicon some HTML content to be added inside the link, before the icon.
return: the HTML for an edit icon, view icon, or nothing for a question

quiz_question_preview_url($quiz, $question, $variant = null, $restartversion = null)   X-Ref

param: stdClass $quiz the quiz settings
param: stdClass $question the question
param: int $variant which question variant to preview (optional).
param: int $restartversion version of the question to use when restarting the preview.
return: moodle_url to preview this question with the options from this quiz.

quiz_question_preview_button($quiz, $question, $label = false, $variant = null, $random = null)   X-Ref

param: stdClass $quiz the quiz settings
param: stdClass $question the question
param: bool $label if true, show the preview question label after the icon
param: int $variant which question variant to preview (optional).
param: bool $random if question is random, true.
return: string the HTML for a preview question icon.

quiz_get_flag_option($attempt, $context)   X-Ref

param: stdClass $attempt the attempt.
param: stdClass $context the quiz context.
return: int whether flags should be shown/editable to the current user for this attempt.

quiz_attempt_state($quiz, $attempt)   X-Ref
Work out what state this quiz attempt is in - in the sense used by
quiz_get_review_options, not in the sense of $attempt->state.

param: stdClass $quiz the quiz settings
param: stdClass $attempt the quiz_attempt database row.
return: int one of the display_options::DURING,

quiz_get_review_options($quiz, $attempt, $context)   X-Ref
The appropriate display_options object for this attempt at this quiz right now.

param: stdClass $quiz the quiz instance.
param: stdClass $attempt the attempt in question.
param: context $context the quiz context.
return: display_options

quiz_get_combined_reviewoptions($quiz, $attempts)   X-Ref
Combines the review options from a number of different quiz attempts.
Returns an array of two ojects, so the suggested way of calling this
funciton is:
list($someoptions, $alloptions) = quiz_get_combined_reviewoptions(...)

param: stdClass $quiz the quiz instance.
param: array $attempts an array of attempt objects.
return: array of two options objects, one showing which options are true for

quiz_send_confirmation($recipient, $a, $studentisonline)   X-Ref
Sends a confirmation message to the student confirming that the attempt was processed.

param: stdClass $recipient user object for the recipient.
param: stdClass $a lots of useful information that can be used in the message
param: bool $studentisonline is the student currently interacting with Moodle?
return: int|false as for {@link message_send()}.

quiz_send_notification($recipient, $submitter, $a)   X-Ref
Sends notification messages to the interested parties that assign the role capability

param: stdClass $recipient user object of the intended recipient
param: stdClass $submitter user object for the user who submitted the attempt.
param: stdClass $a associative array of replaceable fields for the templates
return: int|false as for {@link message_send()}.

quiz_send_notification_messages($course, $quiz, $attempt, $context, $cm, $studentisonline)   X-Ref
Send all the requried messages when a quiz attempt is submitted.

param: stdClass $course the course
param: stdClass $quiz the quiz
param: stdClass $attempt this attempt just finished
param: stdClass $context the quiz context
param: stdClass $cm the coursemodule for this quiz
param: bool $studentisonline is the student currently interacting with Moodle?
return: bool true if all necessary messages were sent successfully, else false.

quiz_send_overdue_message($attemptobj)   X-Ref
Send the notification message when a quiz attempt becomes overdue.

param: quiz_attempt $attemptobj all the data about the quiz attempt.

quiz_attempt_submitted_handler($event)   X-Ref
Handle the quiz_attempt_submitted event.

This sends the confirmation and notification messages, if required.

param: attempt_submitted $event the event object.

quiz_send_notify_manual_graded_message(quiz_attempt $attemptobj, object $userto)   X-Ref
Send the notification message when a quiz attempt has been manual graded.

param: quiz_attempt $attemptobj Some data about the quiz attempt.
param: stdClass $userto
return: int|false As for message_send.

quiz_process_group_deleted_in_course($courseid)   X-Ref
Logic to happen when a/some group(s) has/have been deleted in a course.

param: int $courseid The course ID.
return: void

quiz_get_js_module()   X-Ref
Get the information about the standard quiz JavaScript module.

return: array a standard jsmodule structure.

quiz_question_tostring($question, $showicon = false, $showquestiontext = true,$showidnumber = false, $showtags = false)   X-Ref
Creates a textual representation of a question for display.

param: stdClass $question A question object from the database questions table
param: bool $showicon If true, show the question's icon with the question. False by default.
param: bool $showquestiontext If true (default), show question text after question name.
param: bool $showidnumber If true, show the question's idnumber, if any. False by default.
param: core_tag_tag[]|bool $showtags if array passed, show those tags. Else, if true, get and show tags,
return: string HTML fragment.

quiz_require_question_use($questionid)   X-Ref
Verify that the question exists, and the user has permission to use it.
Does not return. Throws an exception if the question cannot be used.

param: int $questionid The id of the question.

quiz_add_quiz_question($questionid, $quiz, $page = 0, $maxmark = null)   X-Ref
Add a question to a quiz

Adds a question to a quiz by updating $quiz as well as the
quiz and quiz_slots tables. It also adds a page break if required.
param: int $questionid The id of the question to be added
param: stdClass $quiz The extended quiz object as used by edit.php
param: int $page Which page in quiz to add the question on. If 0 (default),
param: float $maxmark The maximum mark to set for this question. (Optional,
return: bool false if the question was already in the quiz

quiz_update_section_firstslots($quizid, $direction, $afterslot, $beforeslot = null)   X-Ref
Move all the section headings in a certain slot range by a certain offset.

param: int $quizid the id of a quiz
param: int $direction amount to adjust section heading positions. Normally +1 or -1.
param: int $afterslot adjust headings that start after this slot.
param: int|null $beforeslot optionally, only adjust headings before this slot.

quiz_add_random_questions($quiz, $addonpage, $categoryid, $number,$includesubcategories, $tagids = [])   X-Ref
Add a random question to the quiz at a given point.

param: stdClass $quiz the quiz settings.
param: int $addonpage the page on which to add the question.
param: int $categoryid the question category to add the question from.
param: int $number the number of random questions to add.
param: bool $includesubcategories whether to include questoins from subcategories.
param: int[] $tagids Array of tagids. The question that will be picked randomly should be tagged with all these tags.

quiz_view($quiz, $course, $cm, $context)   X-Ref
Mark the activity completed (if required) and trigger the course_module_viewed event.

param: stdClass $quiz       quiz object
param: stdClass $course     course object
param: stdClass $cm         course module object
param: stdClass $context    context object

quiz_validate_new_attempt(quiz_settings $quizobj, access_manager $accessmanager, $forcenew, $page, $redirect)   X-Ref
Validate permissions for creating a new attempt and start a new preview attempt if required.

param: quiz_settings $quizobj quiz object
param: access_manager $accessmanager quiz access manager
param: bool $forcenew whether was required to start a new preview attempt
param: int $page page to jump to in the attempt
param: bool $redirect whether to redirect or throw exceptions (for web or ws usage)
return: array an array containing the attempt information, access error messages and the page to jump to in the attempt

quiz_prepare_and_start_new_attempt(quiz_settings $quizobj, $attemptnumber, $lastattempt,$offlineattempt = false, $forcedrandomquestions = [], $forcedvariants = [], $userid = null)   X-Ref
Prepare and start a new attempt deleting the previous preview attempts.

param: quiz_settings $quizobj quiz object
param: int $attemptnumber the attempt number
param: stdClass $lastattempt last attempt object
param: bool $offlineattempt whether is an offline attempt or not
param: array $forcedrandomquestions slot number => question id. Used for random questions,
param: array $forcedvariants slot number => variant. Used for questions with variants,
param: int $userid Specific user id to create an attempt for that user, null for current logged in user
return: stdClass the new attempt

quiz_is_overriden_calendar_event(\calendar_event $event)   X-Ref
Check if the given calendar_event is either a user or group override
event for quiz.

param: calendar_event $event The calendar event to check
return: bool

quiz_create_attempt_handling_errors($attemptid, $cmid = null)   X-Ref
Get quiz attempt and handling error.

param: int $attemptid the id of the current attempt.
param: int|null $cmid the course_module id for this quiz.
return: quiz_attempt all the data about the quiz attempt.