Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 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: 2883 lines (110 kb)
Included or required: 3 times
Referenced: 43 times
Includes or requires: 0 files

Defines 3 classes

Defines 13 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_update_sumgrades()
  quiz_update_all_attempt_sumgrades()
  quiz_set_grade()
  quiz_save_best_grade()
  quiz_calculate_best_grade()
  quiz_update_all_final_grades()
  quiz_override_summary()
  quiz_update_open_attempts()
  quiz_get_attempt_usertime_sql()
  quiz_calculate_best_attempt()
  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_groups_member_added_handler()
  quiz_groups_member_removed_handler()
  quiz_groups_group_deleted_handler()
  quiz_process_group_deleted_in_course()
  quiz_groups_members_removed_handler()
  quiz_get_js_module()

Class: mod_quiz_display_options  - X-Ref

An extension of question_display_options that includes the extra options used
by the quiz.

make_from_quiz($quiz, $when)   X-Ref
Set up the various options from the quiz settings, and a time constant.

param: object $quiz the quiz settings.
param: int $one of the {@link DURING}, {@link IMMEDIATELY_AFTER},
return: mod_quiz_display_options set up appropriately.

extract($bitmask, $bit,$whenset = self::VISIBLE, $whennotset = self::HIDDEN)   X-Ref
No description

Class: qubaids_for_quiz  - X-Ref

A {@link qubaid_condition} for finding all the question usages belonging to
a particular quiz.

__construct($quizid, $includepreviews = true, $onlyfinished = false)   X-Ref
No description

Class: qubaids_for_quiz_user  - X-Ref

A {@link qubaid_condition} for finding all the question usages belonging to a particular user and quiz combination.

__construct($quizid, $userid, $includepreviews = true, $onlyfinished = false)   X-Ref
Constructor for this qubaid.

param: int     $quizid The quiz to search.
param: int     $userid The user to filter on
param: bool    $includepreviews Whether to include preview attempts
param: bool    $onlyfinished Whether to only include finished attempts or not

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

param: object $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_has_question_use($quiz, $slot)   X-Ref
Verify that the question exists, and the user has permission to use it.

param: object $quiz the quiz settings.
param: int $slot which question in the quiz to test.
return: bool whether the user can use this 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: object $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 $quizobj, quiz_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 $quizobj quiz object
param: quiz_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 $quizobj, $attemptnumber, $lastattempt,$offlineattempt = false, $forcedrandomquestions = [], $forcedvariants = [], $userid = null)   X-Ref
Prepare and start a new attempt deleting the previous preview attempts.

param: quiz $quizobj quiz object
param: int $attemptnumber the attempt number
param: object $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: object 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_retrieve_tags_for_slot_ids($slotids)   X-Ref
Retrieves tag information for the given list of quiz slot ids.
Currently the only slots that have tags are random question slots.

Example:
If we have 3 slots with id 1, 2, and 3. The first slot has two tags, the second
has one tag, and the third has zero tags. The return structure will look like:
[
1 => [
quiz_slot_tags.id => { ...tag data... },
quiz_slot_tags.id => { ...tag data... },
],
2 => [
quiz_slot_tags.id => { ...tag data... },
],
3 => [],
]

param: int[] $slotids The list of id for the quiz slots.
return: array[] List of quiz_slot_tags records indexed by slot id.

quiz_create_attempt_handling_errors($attemptid, $cmid = null)   X-Ref
No description

Functions that are not part of a class:

quiz_create_attempt(quiz $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: object $quizobj the quiz object to create an attempt for.
param: int $attemptnumber the sequence number for the attempt.
param: stdClass|null $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 $userid  the id of the user attempting this quiz.
return: object the newly created attempt object.

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

param: quiz      $quizobj            the quiz object to start an attempt for.
param: question_usage_by_activity $quba
param: object    $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: object   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: object                        $attempt      this attempt
param: object                        $lastattempt  last attempt
return: object                       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                       $quizobj
param: question_usage_by_activity $quba
param: object                     $attempt
return: object                    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: object $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: object $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: object $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: object $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: object $quiz the quiz settings.
param: object $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: object $quiz the quiz database row.
return: bool Whether this quiz has any non-blank feedback text.

quiz_update_sumgrades($quiz)   X-Ref
Update the sumgrades field of the quiz. This needs to be called whenever
the grading structure of the quiz is changed. For example if a question is
added or removed, or a question weight is changed.

You should call {@link quiz_delete_previews()} before you call this function.

param: object $quiz a quiz.

quiz_update_all_attempt_sumgrades($quiz)   X-Ref
Update the sumgrades field of the attempts at a quiz.

param: object $quiz a quiz.

quiz_set_grade($newgrade, $quiz)   X-Ref
The quiz grade is the maximum that student's results are marked out of. When it
changes, the corresponding data in quiz_grades and quiz_feedback needs to be
rescaled. After calling this function, you probably need to call
quiz_update_all_attempt_sumgrades, quiz_update_all_final_grades and
quiz_update_grades.

param: float $newgrade the new maximum grade for the quiz.
param: object $quiz the quiz we are updating. Passed by reference so its
return: bool indicating success or failure.

quiz_save_best_grade($quiz, $userid = null, $attempts = array()   X-Ref
Save the overall grade for a user at a quiz in the quiz_grades table

param: object $quiz The quiz for which the best grade is to be calculated and then saved.
param: int $userid The userid to calculate the grade for. Defaults to the current user.
param: array $attempts The attempts of this user. Useful if you are
return: bool Indicates success or failure.

quiz_calculate_best_grade($quiz, $attempts)   X-Ref
Calculate the overall grade for a quiz given a number of attempts by a particular user.

param: object $quiz    the quiz settings object.
param: array $attempts an array of all the user's attempts at this quiz in order.
return: float          the overall grade

quiz_update_all_final_grades($quiz)   X-Ref
Update the final grade at this quiz for all students.

This function is equivalent to calling quiz_save_best_grade for all
users, but much more efficient.

param: object $quiz the quiz settings.

quiz_override_summary(stdClass $quiz, 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: stdClass|cm_info $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_calculate_best_attempt($quiz, $attempts)   X-Ref
Return the attempt with the best grade for a quiz

Which attempt is the best depends on $quiz->grademethod. If the grade
method is GRADEAVERAGE then this function simply returns the last attempt.
param: object $quiz    The quiz for which the best grade is to be calculated
param: array $attempts An array of all the attempts of the user at the quiz
return: object         The attempt with the best grade

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: object 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 {@link 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: object $quiz the quiz.
param: int $cmid the course_module object for this quiz.
param: object $question the question.
param: string $returnurl url to return to after action is done.
param: int $variant which question variant to preview (optional).
param: bool $random if question is random, true.
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: object $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: object $quiz the quiz settings
param: object $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: object $quiz the quiz settings
param: object $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: object $attempt the attempt.
param: object $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: object $quiz the quiz settings
param: object $attempt the quiz_attempt database row.
return: int one of the mod_quiz_display_options::DURING,

quiz_get_review_options($quiz, $attempt, $context)   X-Ref
The the appropraite mod_quiz_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: mod_quiz_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: object $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: object $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: object $recipient user object of the intended recipient
param: object $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: object $course the course
param: object $quiz the quiz
param: object $attempt this attempt just finished
param: object $context the quiz context
param: object $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: object $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: object $userto
return: int|false As for message_send.

quiz_groups_member_added_handler($event)   X-Ref
Handle groups_member_added event

param: object $event the event object.

quiz_groups_member_removed_handler($event)   X-Ref
Handle groups_member_removed event

param: object $event the event object.

quiz_groups_group_deleted_handler($event)   X-Ref
Handle groups_group_deleted event

param: object $event the event object.

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_groups_members_removed_handler($event)   X-Ref
Handle groups_members_removed event

param: object $event the event object.

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

return: array a standard jsmodule structure.